datagridview分页实现

在系统设计应用中,有时候我们需要分页显示数据,这样可以提高用户的体验,还可以提升加载速度。网上已经有很多关于DataGridView分页功能函数的相关代码,我当时也尝试使用他们提供的方案,但是真正运用到项目中,代码无法跑起来,也存在一些错误。今天,我将分享如何实现DataGridView分页功能。控件效果图如下:


首先我们需要获取当前页,默认当前页的索引为1,即我们定义一个私有变量 private int _PageIndex=1;点击_PageInde按下Ctrl+R、Ctrl+E就可以将当前字段封装起来,然后我们连续创建几个字段分别为PageSize(页面记录数)、StartIndex(当前页面开始行)、EndIndex(当前页面结束行)、RecordCount(总记录数)、PageCount(总页面数)等等,具体定义可在完整代码当中查看。我们将所有的属性字段写好之后,我们往控件上添加分页常用的几个上一页、下一页、首页、尾页已经制定页数跳转。

控件做完之后,看看怎么使用该控件,我们将控件拖放在需要分页的模块,在datagridview大小改变事件中,设置分页大小=(当前datagridview的高度-表头高度-滚动条高度)/(表格行模板高度)。

        #region 大小改变事件
        private void skinDataGridView_SizeChanged(object sender, EventArgs e)
        {
            pagingControl1.PageSize = ((skinDataGridView.Height - skinDataGridView.ColumnHeadersHeight - 17) / skinDataGridView.RowTemplate.Height);            
        }
        #endregion

设置完分页大小,接着赋值总数目,总数目赋值后,控件内的相关方法会进行计算当前可以分几页,最后就是向数据库索取值,我们可以定义如下的方法获取数据。

DataTable GetDataTable(int pageIndex,int pageSize,string strWhere,out int totalCount)

     紧接着我们说说如何在SQL写分页数据,直接上代码

    #region 数据分页查询语句
        public DataTable GetDataTable(int pageIndex, int pageSize, string strWhere,out int totalCount)
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat(@"SELECT TOP {0} * FROM (", pageSize);
            sql.Append("SELECT ROW_NUMBER() OVER (ORDER BY ID DESC) AS RowNumber,");         
            sql.Append("写你要查询的SQL语言 ");          
            sql.Append(") AS A");
            sql.AppendFormat(" WHERE RowNumber >{0}*({1}-1)", pageSize, pageIndex);
            //执行您要操作的SQL语法
           //totalCount这边的值是你不限制查询第几条 统计所有的数量 例如:SELECT COUNT(ID) FROM Table
         }      
      #endregion
至此,我们就实现好分页功能了,附上控件设计的CS完整代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SCommon.UserControls
{
    // 分页控件
    public partial class PagingControl : UserControl
    {
        public PagingControl()
        {
            InitializeComponent();
        }

        // 当前页
        private int pageIndex = 1;
        // 页面记录数
        private int pageSize = 10;
        // 当前页面开始行
        private int startIndex;
        // 当前页面结束行
        private int endIndex;
        // 总记录数
        private int recordCount = 0;
        // 总页面数
        private int pageCount = 1;
        // 跳转页面
        private string jumpIndex = string.Empty;

        /// <summary>
        /// 当前页
        /// </summary>
        public int PageIndex
        {
            get { return this.pageIndex; }
            set { this.pageIndex = value; }
        }
        /// <summary>
        /// 页面记录数
        /// </summary>
        public int PageSize
        {
            get { return this.pageSize; }
            set { this.pageSize = value; }
        }

        /// <summary>
        /// 当前页面开始行
        /// </summary>
        public int StartIndex
        {
            get
            {
                startIndex = (PageIndex - 1 <= 0 ? 0 : PageIndex - 1) * (PageSize <= 0 ? 1 : PageSize) + 1;
                return startIndex;
            }
        }
        /// <summary>
        /// 当前页面结束行
        /// </summary>
        public int EndIndex
        {
            get
            {
                endIndex = PageIndex * (PageSize <= 0 ? 0 : PageSize);
                return endIndex;
            }
        }
        /// <summary>
        /// 总记录数
        /// </summary>
        public int RecordCount
        {
            get { return this.recordCount; }
            set
            {
                this.recordCount = value;
                GetPageCount();
                DrawControl(false);
            }
        }
        /// <summary>
        /// 总页面数
        /// </summary>
        public int PageCount
        {
            get
            {
                this.pageCount = GetPageCount();
                return this.pageCount;
            }
            //set { this.pageCount = value; }
        }

        /// <summary>
        /// 跳转页面
        /// </summary>
        public string JumpIndex
        {
            get { return this.jumpIndex; }
            set { this.jumpIndex = value; }
        }

        /// <summary>
        /// 计算总页面数
        /// </summary>
        /// <returns></returns>
        private int GetPageCount()
        {
            if (PageSize <= 0)
            {
                return 1;
            }
            int page_Count = RecordCount / PageSize;
            if (RecordCount % PageSize != 0)
            {
                page_Count++;
            }
            return page_Count;
        }

        /// <summary>
        /// 页数改变事件
        /// </summary>
        public event EventHandler OnPageChanged;

        /// <summary>
        /// 重绘控件
        /// </summary>
        private void DrawControl(bool callEvent)
        {
            labRecordCount.Text = RecordCount + "行";
            labPageIndex.Text = PageIndex.ToString();
            labPageCount.Text = PageCount.ToString();
            txtPageIndex.Text = JumpIndex;

            if (PageCount == 1)
            {
                btnFirst.Enabled = false;
                btnPrev.Enabled = false;
                btnNext.Enabled = false;
                btnLast.Enabled = false;
            }
            if (PageIndex == 1)
            {
                btnFirst.Enabled = false;
                btnPrev.Enabled = false;
                btnNext.Enabled = true;
                btnLast.Enabled = true;
            }
            else if (PageIndex == PageCount)
            {
                btnFirst.Enabled = true;
                btnPrev.Enabled = true;
                btnNext.Enabled = false;
                btnLast.Enabled = false;
            }
            else
            {
                btnFirst.Enabled = true;
                btnPrev.Enabled = true;
                btnNext.Enabled = true;
                btnLast.Enabled = true;
            }
            if (callEvent && OnPageChanged != null)
            {
                OnPageChanged(this, null);//当前分页数字改变时,触发委托事件
            }
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFirst_Click(object sender, EventArgs e)
        {
            PageIndex = 1;
            DrawControl(true);
        }
        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrev_Click(object sender, EventArgs e)
        {
            PageIndex = Math.Max(1, PageIndex - 1);
            DrawControl(true);
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNext_Click(object sender, EventArgs e)
        {
            PageIndex = Math.Min(PageIndex + 1, PageCount);
            DrawControl(true);
        }
        /// <summary>
        /// 尾页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLast_Click(object sender, EventArgs e)
        {
            PageIndex = PageCount;
            DrawControl(true);
        }

        private void txtPageIndex_TextChanged(object sender, EventArgs e)
        {
            if (txtPageIndex.Text.Trim() != string.Empty && txtPageIndex.Text.Trim() != JumpIndex)
            {
                int index = 0;
                if (!int.TryParse(txtPageIndex.Text.Trim(), out index))
                {
                    txtPageIndex.Text = JumpIndex;
                    return;
                }
            }
            JumpIndex = txtPageIndex.Text.Trim();
        }

        private void txtPageIndex_Leave(object sender, EventArgs e)
        {
            if (txtPageIndex.Text.Trim() != string.Empty && txtPageIndex.Text.Trim() != JumpIndex)
            {
                int index = 0;
                if (!int.TryParse(txtPageIndex.Text.Trim(), out index))
                {
                    txtPageIndex.Text = JumpIndex;
                    return;
                }
            }
            JumpIndex = txtPageIndex.Text.Trim();
        }
        /// <summary>
        /// 跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnJump_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtPageIndex.Text.Trim()))
            {
                txtPageIndex.Text = "";
                return;
            }
            int index = 0;
            if (!int.TryParse(txtPageIndex.Text.Trim(), out index))
            {
                txtPageIndex.Text = "";
                return;
            }
            if (index <= 0 || index > PageCount)
            {
                txtPageIndex.Text = "";
                return;
            }
            PageIndex = index;
            DrawControl(true);
            txtPageIndex.Text = "";
        }

        private void txtPageIndex_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == '\b')
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
    }
}

评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值