C# Winform 分页功能

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

C# Winform 分页功能_第1张图片 内部代码如下

 #region 分页字段和属性

        private int pageIndex = 1;
        /// 
        /// 当前页数
        /// 
        public virtual int PageIndex
        {
            get { return pageIndex; }
            set { pageIndex = value; }
        }

        private int pageSize = 100;
        /// 
        /// 每页记录数
        /// 
        public virtual int PageSize
        {
            get { return pageSize; }
            set { pageSize = value; }
        }

        private int recordCount = 0;
        /// 
        /// 总记录数
        /// 
        public virtual int RecordCount
        {
            get { return recordCount; }
            set { recordCount = value; }
        }

        private int pageCount = 0;
        /// 
        /// 总页数
        /// 
        public int PageCount
        {
            get
            {
                if (pageSize != 0)
                {
                    pageCount = GetPageCount();
                }
                return pageCount;
            }
        }

        #endregion

        #region 页码变化时触发事件

        public event EventHandler OnPageChanged;

        #endregion
   #region 分页及相关事件功能实现

        /// 
        /// 设窗体控件全部可用
        /// 
        private void SetFormCtrEnabled()
        {
            linkFirst.Enabled = true;
            linkPrevious.Enabled = true;
            linkNext.Enabled = true;
            linkLast.Enabled = true;
            btnGo.Enabled = true;
        }

        /// 
        /// 计算总页数
        /// 
        /// 
        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;
        }
        /// 
        /// 用于客户端调用
        /// 
        public void DrawControl(int count)
        {
            recordCount = count;
            DrawControl(false);
        }
        /// 
        /// 根据不同的条件,改变页面控件的呈现状态
        /// 
        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);
        }

        /// 
        /// 按下enter键,执行跳转页面功能
        /// 
        private void txtPageNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            btnGo_Click(null, null);
        }

        /// 
        /// 跳转页数限制
        /// 
        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();
                }
            }
        }

        /// 
        /// 跳转按钮
        /// 
        /// 
        /// 
        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;
        /// 
        /// 每页显示的记录数改变时
        /// 
        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;
        }
        /// 
        /// 光标离开 每页设置文本框时,显示到首页
        private void txtPageSize_Leave(object sender, EventArgs e)
        {
            if (isTextChanged)
            {
                isTextChanged = false;
                linkFirst_Click(null, null);
            }
        }

 符合我的分页查询方法

 /// 
        /// 通用分页查询方法
        /// 
        /// 表名
        /// 查询字段名
        /// where条件
        /// 排序条件
        /// 每页数据数量
        /// 当前页数
        /// 数据总量
        /// DataTable数据表
        public static List SelectPaging(string tableName, string strColumns, string strWhere, string strOrder, int pageSize, int currentIndex, out int recordOut)
        {
            List 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;
        }

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

/// 
        /// 通用分页查询方法
        /// 
        /// 连接字符串
        /// 表名
        /// 查询字段名
        /// where条件
        /// 排序条件
        /// 每页数据数量
        /// 当前页数
        /// 数据总量
        /// DataTable数据表
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 res = DBHelper.SelectPaging("T_DM_COMPANY", " comId,comCode,comName,configureCode", stringBuilder.ToString(), " configureCode DESC ,comCode", pagerControl1.PageSize, pagerControl1.PageIndex, out RecordCount);

            List list = new List();
            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 templateIps = new List();
            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;
           
        }
     /// 
        /// 分页查询文件数据
        /// 
        /// 文件路径
        /// 每页数量
        /// 当前页数
        /// 数据总量
        /// 
        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 list = new List { };
                // 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();
            }
            return str;
        }

附上运行结果

C# Winform 分页功能_第2张图片

你可能感兴趣的:(Winform,c#)