DataGridView实现简单分页功能

Posted atomy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DataGridView实现简单分页功能相关的知识,希望对你有一定的参考价值。

    本例子使用自定义控件方法实现,数据库使用的是SQL Server,实现过程如下:

    1、新建一个自定义控件,命名为:PageControl。

    技术图片

    2、PageControl代码如下:

    public partial class PageControl : UserControl
    {
        //委托及事件
        public delegate void BindPage(int pageSize, int pageIndex, out int totalCount);
        public event BindPage BindPageEvent;

        //属性
        public int PageSize { get; set; } = 1;  //每页显示记录数
        public int PageIndex { get; set; }      //页序号
        public int TotalCount { get; set; }     //总记录数

        public int PageCount { get; set; }      //总页数

        public PageControl()
        {
            InitializeComponent();
        }

        //设置页
        public void SetPage()
        {
            //总记录数
            int totalCount = 0;
            BindPageEvent(PageSize, PageIndex + 1, out totalCount);
            TotalCount = totalCount;

            //总页数
            if (TotalCount % PageSize == 0)
                PageCount = TotalCount / PageSize;
            else
                PageCount = (int)(TotalCount / PageSize) + 1;

            //序号
            lblSerialNumber.Text = (PageIndex + 1).ToString() + "/" + PageCount.ToString();
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkFirst_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                PageIndex = 0;
                SetPage();
            }
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkPrve_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                PageIndex--;
                if (PageIndex < 0)
                {
                    PageIndex = 0;
                }
                SetPage();
            }
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkNext_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                PageIndex++;
                if (PageIndex > PageCount - 1)
                {
                    PageIndex = PageCount - 1;
                }
                SetPage();
            }
        }

        /// <summary>
        /// 末页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLast_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                PageIndex = PageCount - 1;
                SetPage();
            }
        }

        /// <summary>
        /// 只能输入正整数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtSetPage_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar >= 48 && e.KeyChar <= 57)
                e.Handled = false;
            else
                e.Handled = true;
        }

        /// <summary>
        /// 指定页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkGo_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (string.IsNullOrEmpty( txtSetPage.Text))
                {
                    MessageBox.Show("指定页不能为空。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtSetPage.Focus();
                    return;
                }

                if(int.Parse(txtSetPage.Text)>PageCount)
                {
                    MessageBox.Show("指定页已超过总页数。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtSetPage.Focus();
                    return;
                }

                PageIndex = int.Parse(txtSetPage.Text) - 1;
                SetPage();
            }
        }
    }

    3、SQL Server创建存储过程PageTest:

CREATE PROCEDURE PageTest
    @PageSize int,
    @PageIndex int,
    @TotalCount int OUTPUT
AS
BEGIN
    SELECT @TotalCount=COUNT(1) FROM MF_MO

    SELECT TOP (@PageSize) MO_NO,MRP_NO,QTY,BIL_NO
    FROM MF_MO A
    WHERE NOT EXISTS (SELECT 1 FROM (SELECT TOP ((@PageIndex-1)*@PageSize) MO_NO FROM MF_MO) B WHERE A.MO_NO=B.MO_NO)
END

    4、新建一个WinForm程序,命名为Main,并拖入一个DataGridView控件及上面新建的PageControl控件,代码如下:

        private void Main_Load(object sender, EventArgs e)
        {
            pageControl1.PageSize = 20;
            pageControl1.PageIndex = 0;
            pageControl1.BindPageEvent += BindPage;
            pageControl1.SetPage();
        }

        private void BindPage(int pageSize, int pageIndex, out int totalCount)
        {
            SqlConnection conn = null;
            SqlCommand cmd = null;
            totalCount = 0;

            #region 连接数据库测试
            try
            {
                //数据库连接
                conn = new SqlConnection("server=.;database=DB_TEST;Uid=sa;pwd=********;");
                conn.Open();

                //SqlCommand
                cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "PageTest";
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter[] param =
                {
                    new SqlParameter("@PageSize",SqlDbType.Int),
                    new SqlParameter("@PageIndex",SqlDbType.Int),
                    new SqlParameter("@TotalCount",SqlDbType.Int)
                };
                param[0].Value = pageSize;
                param[1].Value = pageIndex;
                param[2].Direction = ParameterDirection.Output;
                cmd.Parameters.AddRange(param);

                //DataTable
                DataTable dt = new DataTable("MF_MO");
                dt.Columns.Add(new DataColumn("MO_NO", typeof(String)));
                dt.Columns.Add(new DataColumn("MRP_NO", typeof(String)));
                dt.Columns.Add(new DataColumn("QTY", typeof(Decimal)));
                dt.Columns.Add(new DataColumn("BIL_NO", typeof(String)));

                #region 方法一:SqlDataReader
                SqlDataReader dr = cmd.ExecuteReader();
                dt.Load(dr, LoadOption.PreserveChanges);
                dr.Close();
                totalCount = (int)param[2].Value;
                dataGridView1.DataSource = dt;
                #endregion

                #region #方法二:SqlDataAdapter
                //SqlDataAdapter da = new SqlDataAdapter();
                //da.SelectCommand = cmd;
                //dt.BeginLoadData();
                //da.Fill(dt);
                //dt.EndLoadData();
                //totalCount = (int)param[2].Value;
                //dataGridView1.DataSource = dt;
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                conn.Close();
                cmd.Dispose();
            }
            #endregion
        }

    5、执行程序:

技术图片

    感觉在200页以内,速度还是可以接受。

    好了,分享就到此结束了,希望对有此需要的人有一些帮助。

    

以上是关于DataGridView实现简单分页功能的主要内容,如果未能解决你的问题,请参考以下文章

winform中DataGridView实现分页功能

winform中的DataGridView如何实现分页(C#)

C#怎么实现 DataGridView分页功能

c#DataGridview 分页功能怎么实现

winform中的DataGridView如何实现分页(C#)

DataGridView分页功能的实现