文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

C#Winform分页功能的实现

2024-04-02 19:55

关注

首先创建一个用户控件 如下图 用到的控件 label、button、TextBox

 内部代码如下

 #region 分页字段和属性
 
        private int pageIndex = 1;
        /// <summary>
        /// 当前页数
        /// </summary>
        public virtual int PageIndex
        {
            get { return pageIndex; }
            set { pageIndex = value; }
        }
 
        private int pageSize = 100;
        /// <summary>
        /// 每页记录数
        /// </summary>
        public virtual int PageSize
        {
            get { return pageSize; }
            set { pageSize = value; }
        }
 
        private int recordCount = 0;
        /// <summary>
        /// 总记录数
        /// </summary>
        public virtual int RecordCount
        {
            get { return recordCount; }
            set { recordCount = value; }
        }
 
        private int pageCount = 0;
        /// <summary>
        /// 总页数
        /// </summary>
        public int PageCount
        {
            get
            {
                if (pageSize != 0)
                {
                    pageCount = GetPageCount();
                }
                return pageCount;
            }
        }
 
        #endregion
 
        #region 页码变化时触发事件
 
        public event EventHandler OnPageChanged;
 
        #endregion
   #region 分页及相关事件功能实现
 
        /// <summary>
        /// 设窗体控件全部可用
        /// </summary>
        private void SetFormCtrEnabled()
        {
            linkFirst.Enabled = true;
            linkPrevious.Enabled = true;
            linkNext.Enabled = true;
            linkLast.Enabled = true;
            btnGo.Enabled = true;
        }
 
        /// <summary>
        /// 计算总页数
        /// </summary>
        /// <returns></returns>
        private int GetPageCount()
        {
            if (PageSize == 0)
            {
                return 0;
            }
            int pageCount = RecordCount / PageSize;
            if (RecordCount % PageSize == 0)
            {
                pageCount = RecordCount / PageSize;
            }
            else
            {
                pageCount = RecordCount / PageSize + 1;
            }
            return pageCount;
        }
        /// <summary>
        /// 用于客户端调用
        /// </summary>
        public void DrawControl(int count)
        {
            recordCount = count;
            DrawControl(false);
        }
        /// <summary>
        /// 根据不同的条件,改变页面控件的呈现状态
        /// </summary>
        private void DrawControl(bool callEvent)
        {
 
            lblCurrentPage.Text = PageIndex.ToString();
            lblPageCount.Text = PageCount.ToString();
            lblTotalCount.Text = RecordCount.ToString();
            txtPageSize.Text = PageSize.ToString();
 
            if (callEvent && OnPageChanged != null)
            {
                OnPageChanged(this, null);//当前分页数字改变时,触发委托事件
            }
            SetFormCtrEnabled();
            if (PageCount == 1)//有且仅有一页时
            {
                linkFirst.Enabled = false;
                linkPrevious.Enabled = false;
                linkNext.Enabled = false;
                linkLast.Enabled = false;
                btnGo.Enabled = false;
            }
            else if (PageIndex == 1)//当前页为第一页时
            {
                linkFirst.Enabled = false;
                linkPrevious.Enabled = false;
            }
            else if (PageIndex == PageCount)//当前页为最后一页时
            {
                linkNext.Enabled = false;
                linkLast.Enabled = false;
            }
        }
 
        #endregion
 
 
        #region 相关控件事件
 
        //首页按钮
        private void linkFirst_Click(object sender, EventArgs e)
        {
            PageIndex = 1;
            DrawControl(true);
        }
 
        //上一页按钮
        private void linkPrevious_Click(object sender, EventArgs e)
        {
            PageIndex = Math.Max(1, PageIndex - 1);
            DrawControl(true);
        }
 
        //下一页按钮
        private void linkNext_Click(object sender, EventArgs e)
        {
            PageIndex = Math.Min(PageCount, PageIndex + 1);
            DrawControl(true);
        }
 
        //尾页按钮
        private void linkLast_Click(object sender, EventArgs e)
        {
            PageIndex = PageCount;
            DrawControl(true);
        }
 
        /// <summary>
        /// 按下enter键,执行跳转页面功能
        /// </summary>
        private void txtPageNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            btnGo_Click(null, null);
        }
 
        /// <summary>
        /// 跳转页数限制
        /// </summary>
        private void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int num = 0;
            if (int.TryParse(txtPageNum.Text.Trim(), out num) && num > 0)
            {   //TryParse 函数,将字符串转换成等效的整数,返回bool型,判断是否转换成功。
                //输入除数字以外的字符是转换不成功的
 
                if (num > PageCount)   //输入数量大于最大页数时,文本框自动显示最大页数
                {
                    txtPageNum.Text = PageCount.ToString();
                }
            }
        }
 
        /// <summary>
        /// 跳转按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGo_Click(object sender, EventArgs e)
        {
            int num = 0;
            if (int.TryParse(txtPageNum.Text.Trim(), out num) && num > 0)
            {
                PageIndex = num;
                DrawControl(true);
            }
        }
 
        #endregion
        bool isTextChanged = false;
        /// <summary>
        /// 每页显示的记录数改变时
        /// </summary>
        private void txtPageSize_TextChanged(object sender, EventArgs e)
        {
            int num = 0;
            //输入不符合规范时,默认设置为100
            if (!int.TryParse(txtPageSize.Text.Trim(), out num) || num <= 0)
            {
                num = 100;
                txtPageSize.Text = "100";
            }
            else
            {
                isTextChanged = true;
 
            }
            pageSize = num;
        }
        /// <summary>
        /// 光标离开 每页设置文本框时,显示到首页
        private void txtPageSize_Leave(object sender, EventArgs e)
        {
            if (isTextChanged)
            {
                isTextChanged = false;
                linkFirst_Click(null, null);
            }
        }

 符合我的分页查询方法

 /// <summary>
        /// 通用分页查询方法
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="strColumns">查询字段名</param>
        /// <param name="strWhere">where条件</param>
        /// <param name="strOrder">排序条件</param>
        /// <param name="pageSize">每页数据数量</param>
        /// <param name="currentIndex">当前页数</param>
        /// <param name="recordOut">数据总量</param>
        /// <returns>DataTable数据表</returns>
        public static List<String[]> SelectPaging(string tableName, string strColumns, string strWhere, string strOrder, int pageSize, int currentIndex, out int recordOut)
        {
            List<String[]> res;
            recordOut = Convert.ToInt32(search(string.Format("select count(*) from {0} where{1}" ,tableName, strWhere))[0][0]);
            string pagingTemplate = "select {0} from {1} where {2} order by {3} limit {4} offset {5} ";
            int offsetCount = (currentIndex - 1) * pageSize;
            string commandText = String.Format(pagingTemplate, strColumns, tableName, strWhere, strOrder, pageSize.ToString(), offsetCount.ToString());
            res = search(commandText);
            return res;
        }

附上我修改前的分页查询方法

/// <summary>
        /// 通用分页查询方法
        /// </summary>
        /// <param name="connString">连接字符串</param>
        /// <param name="tableName">表名</param>
        /// <param name="strColumns">查询字段名</param>
        /// <param name="strWhere">where条件</param>
        /// <param name="strOrder">排序条件</param>
        /// <param name="pageSize">每页数据数量</param>
        /// <param name="currentIndex">当前页数</param>
        /// <param name="recordOut">数据总量</param>
        /// <returns>DataTable数据表</returns>
public static DataTable SelectPaging(string tableName, string strColumns, string strWhere, string strOrder, int pageSize, int currentIndex, out int recordOut)
        {
            DataTable dt = new DataTable();
            recordOut = Convert.ToInt32(ExecuteScalar( "select count(*) from " + tableName));
            string pagingTemplate = "select {0} from {1} where {2} order by {3} limit {4} offset {5} ";
            int offsetCount = (currentIndex - 1) * pageSize;
            string commandText = String.Format(pagingTemplate, strColumns, tableName, strWhere, strOrder, pageSize.ToString(), offsetCount.ToString());
            DataSet ds= ExecuteDataSet(commandText);
            dt = ds.Tables[0];
            return dt;
        }

 两种使用方式

 1、数据库查询

    private void pagerControl1_OnPageChanged(object sender, EventArgs e)
        {
            initData();
        }
 
   public CompanyData()
        {
            InitializeComponent();
            initData();
            //激活OnPageChanged事件
            pagerControl1.OnPageChanged += new EventHandler(pagerControl1_OnPageChanged);
        }
 
  private void initData()
        {
            
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(" 1=1 ");
            if (this.TbComName.Text != "")
            {
                stringBuilder.Append("and comName like '%" + this.TbComName.Text + "%'");
            }
            int RecordCount;
            List<String[]> res = DBHelper.SelectPaging("T_DM_COMPANY", " comId,comCode,comName,configureCode", stringBuilder.ToString(), " configureCode DESC ,comCode", pagerControl1.PageSize, pagerControl1.PageIndex, out RecordCount);
 
            List<Company> list = new List<Company>();
            for (int i = 0; i < res.Count; i++)
            {
                list.Add(new Company(res[i]));
            }
            pagerControl1.DrawControl(RecordCount);
 
            BindingSource bs = new BindingSource();
            bs.DataSource = list;
            this.CompanyDataDGW.DataSource = bs;
        }

 2、文件读取数据 分页

  private void pagerControl1_OnPageChanged(object sender, EventArgs e)
        {
            Init();
        }
 public ProductionConfig()
        {
            InitializeComponent();
            Init();
 
            //激活OnPageChanged事件
            pagerControl1.OnPageChanged += new EventHandler(pagerControl1_OnPageChanged);
        }
  private void Init()
        {
            //获取template 中ip配置文件信息
            //String[] temIp = PropertiesGenerateUtil.getTemplate("template/ip.properties");
            int RecordCount;
            String[] temIp = PropertiesGenerateUtil.getTemplatePaging("template/ip.properties",pagerControl1.PageSize,pagerControl1.PageIndex,out RecordCount);
            List<entity.templateIp> templateIps = new List<entity.templateIp>();
            foreach (var item in temIp)
            {
                templateIps.Add(new entity.templateIp(item.Substring(0, item.IndexOf("="))));
            }
 
            pagerControl1.DrawControl(RecordCount);
 
            BindingSource bs = new BindingSource();
            bs.DataSource = templateIps;
            this.DGVTemplateIp.DataSource = bs;
           
        }
     /// <summary>
        /// 分页查询文件数据
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="pageSize">每页数量</param>
        /// <param name="currentIndex">当前页数</param>
        /// <param name="recordOut">数据总量</param>
        /// <returns></returns>
        public static string[] getTemplatePaging(string path, int pageSize, int currentIndex, out int recordOut)
        {
            string[] str;
            recordOut = getTemplate(path).Count();
            using (StreamReader sr = new StreamReader(path))
            {
                string line;
                List<string> list = new List<string> { };
                // 1 0 1*100
                // 2 100 2*100
                int startingValue = (currentIndex - 1) * pageSize;//起始值
                int terminationValue = currentIndex * pageSize;//终止值
                int tempValue = 0;//计数器
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.Contains("#"))//判断是注释跳出
                        continue;
                    if(tempValue>=startingValue&&tempValue< terminationValue)//判断是起始值添加
                        list.Add(line);
                    if (tempValue == terminationValue)//判断是终止值跳出
                        break;
                    tempValue++;
                }
                str = list.ToArray<String>();
            }
            return str;
        }

附上运行结果

到此这篇关于C# Winform 分页功能的实现的文章就介绍到这了,更多相关C# Winform 分页内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯