DataGridView分頁控件

本文介绍如何在Visual Studio中创建一个自定义的Windows Forms分页控件,详细展示了控件的代码实现,包括页数计算、翻页事件处理等功能,并在其他项目中如何引用和使用该控件进行数据分页显示。通过事件处理和Linq查询,实现了动态加载分页数据到数据网格视图。
摘要由CSDN通过智能技术生成

效果如下:

在这里插入图片描述
在这里插入图片描述

一、在vs中新建一個 WindowsFormsControlLibrary項目
1.拖入相關的控件
在这里插入图片描述

2.代碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LWF_PageControl
{
    public partial class LwfPageControl: UserControl
    {
        public LwfPageControl()
        {
            InitializeComponent();            
        }
        #region fields & properties
        //current row number from
        public virtual int CurRowIndexFrom
        { get; set; }
        //current row number to
        public virtual int CurRowIndexTo
        { get; set; }
        /// <summary>
        /// Current Page
        /// </summary>
        private int _PageIndex=1;
        public virtual int PageIndex
        {
            get { return _PageIndex; }
            set { _PageIndex = value; }
        }
        /// <summary>
        /// PageSize
        /// </summary>
        private int _PageSize = 100; //值可以在控件屬性中設置
        public virtual int PageSize
        {
            get { return _PageSize; }
            set { _PageSize = value; }
        }
        /// <summary>
        /// Record count
        /// </summary>
        private int _RecordCount = 0;
        public virtual int RecordCount
        {
            get { return _RecordCount; }
           // set { _RecordCount = value; }
        }
        /// <summary>
        /// Page count
        /// </summary>
        private int _PageCount = 0;
        public  int PageCount
        {
            get
            {
                if (PageSize != 0)
                {
                    _PageCount = GetPageCount();
                }
                return _PageCount;
            }

        }

        #endregion

        #region the event when page is changed

        public event EventHandler OnPageChanged;

        #endregion

# region PageControl Event and funtions

        /// <summary>
        /// set controls (button) enabled
        /// </summary>
        private void setControlEnabled()
        {
            btnFirst.Enabled = btnGo.Enabled = btnLast.Enabled = btnNextPage.Enabled = btnPrewPage.Enabled = true;            
        }
        /// <summary>
        /// Get the Page count
        /// </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>
        /// invoke for the client
        /// </summary>
        /// <param name="count"></param>
        public void DrawControl(int count)
        {
            _RecordCount = count;
            DrawControl(false);
        }

        private void DrawControl(bool callEvent)
        {
            txtCurPage.Text = PageIndex.ToString();
            lblOfTolPage .Text = string.Format(" of {0}", PageCount.ToString());
            txtPageSize.Text = PageSize.ToString();
            CurRowIndexFrom = (PageIndex - 1) * PageSize + 1;
            CurRowIndexTo = PageIndex *PageSize > RecordCount ? RecordCount : (PageIndex * PageSize);
            lblRowInfo.Text = string.Format("{0} to {1} of [{2}]", CurRowIndexFrom.ToString(), CurRowIndexTo.ToString (), RecordCount.ToString());       

            if (callEvent && OnPageChanged != null)
            {
                OnPageChanged(this, null);
            }
            setControlEnabled();
            if (PageCount == 1) //when the page equal 1
            {
                btnFirst.Enabled = btnGo.Enabled = btnLast.Enabled = btnNextPage.Enabled = btnPrewPage.Enabled = false;
            }
            else
                if (PageIndex == 1)
            {
                btnFirst.Enabled = btnPrewPage.Enabled = false;
            }
            if (PageIndex == PageCount)
            {
                btnLast.Enabled = btnNextPage.Enabled = false;
            }

        }
        #endregion

        #region button control event



        private void btnFirst_Click(object sender, EventArgs e)
        {
            PageIndex = 1;
            DrawControl(true);
        }



        
        private void btnPrewPage_Click(object sender, EventArgs e)
        {
            PageIndex = Math.Max(1, PageIndex - 1);
            DrawControl(true);
        }

        private void btnNextPage_Click(object sender, EventArgs e)
        {
            PageIndex = Math.Min(PageCount, PageIndex + 1);
            DrawControl(true);
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            PageIndex = PageCount;
            DrawControl(true);
        }


        private void btnGo_Click(object sender, EventArgs e)
        {
            int num = 0;
            if (int.TryParse(txtCurPage.Text.Trim(), out num) && num > 0)
            {
                PageIndex = num;
                DrawControl(true);
            }

        }

        /// <summary>
        ///press enter in the textbox to page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbToPage_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)(13))
            {
                btnGo_Click(null, null);
            }
        }
        #endregion

        private void tbToPage_TextChanged(object sender, EventArgs e)
        {
            int num = 0;
            if (int.TryParse(txtCurPage.Text, out num) && num > 0)
            {
                if (num > PageCount)
                {
                    txtCurPage.Text = PageCount.ToString();// the max page is Pagecount
                }
            }
        }

        private bool isTxtPageSizeChanged = false;

        private  void txtPageSize_TextChanged(object sender, EventArgs e)
        {
            int num = 0;
            if (!int.TryParse(txtPageSize.Text.Trim(), out num) || num < 0)
            {
                num = 100;
                txtPageSize.Text = "100";
            }
            else
            {
                isTxtPageSizeChanged = true;
            }
            _PageSize = num;
        }
        /// <summary>
        /// when changed the pagesize , go to the first page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPageSize_Leave(object sender, EventArgs e)
        {
            if (isTxtPageSizeChanged)
            {
                isTxtPageSizeChanged = false;
                btnFirst_Click(null, null);
            }
        }
    }
}

編譯后就可以給其它項目使用

二、在其它項目窗體中使用

1.引用該控件dll
2.在右邊控件欄空白處右擊,選擇項目–》瀏覽–》找到該控件dll , 確定后就可看到該控件了。
3.將控件拉入窗體中
4.代碼調用:

**例子:
分解1**
        private void Form1_Load(object sender, EventArgs e)
        {            
            //激活OnPageChanged事件。 lwfPageControl1:控件名稱
            lwfPageControl1.OnPageChanged += lwfPageControl1_OnPageChanged;    
        }
        
**分解2**
 /// <summary>
        /// 查詢按鈕事件
        /// </summary>
        private void SearchEvent()
        {
            //得到全部查詢結果,注意用 Row_Number() 作為分頁的記錄篩選,然後在下面再用Linq 取出分頁記錄。 當然也可以(使用存儲過程)每次取出第 M ----N 個記錄,也是比較常用方法。
            DataSet ds = sqlherpler.GetData("SELECT Row_Number() over (order by id) as rowindex,* FROM Employee", null);
            queryTable = ds.Tables[0];//員工表  
            //調用pageControl 加載數據事件
            LoadData_ForPageControl();
        }
        
**分解3**
 /// <summary>
        /// 加载数据--for PageControl 
        /// </summary>
        private void LoadData_ForPageControl()
        {               
            int count = queryTable.Rows.Count; //查詢結果的記錄數
            lwfPageControl2.DrawControl(count);
            //使用Linq 在查詢結果表中取第 M ----N 個記錄.  
            var query = queryTable.AsEnumerable().Where((o) => int.Parse(o["rowindex"].ToString ()) >= lwfPageControl1.CurRowIndexFrom && int.Parse(o["rowindex"].ToString()) <= lwfPageControl1.CurRowIndexTo);
             dgv1.DataSource = query.Any() ? query.CopyToDataTable<DataRow>().DefaultView : null;                   
        }
        
       /// <summary>
       /// 控件分頁按鈕事件
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private void lwfPageControl1_OnPageChanged(object sender, EventArgs e)
        {
            LoadData_ForPageControl();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值