C# WinForm自定義通用分頁控件


 

 

  大家好,前幾天因工作需要要開發一個基於WinForm的小程序。其中要用到分頁,最開始的想法找個第三方的dll用一下,但是后來想了想覺得不如自己寫一個玩一下 之前的web開發中有各式各樣的列表組件基本都帶有分頁功能,筆者早先也自己寫過B/S端的分頁組件(利用jquery純前端方式)。對於WinForm的還是第一次。當完成后發現其實要比B/S端的簡單,基本上都是基於各種控件的事件和委托來實現的。后面會介紹到委托和事件在自定義組合用戶控件中的使用。

---------------------------------------------------------------------------------------------以下進入正題-------------------------------------------------------------------------------------------------------------------

一、創建一個WinForm項目,我用的是VS2013 基本上VS其他版本都差不多一樣

建立一個名字叫UserPageControlDemo的項目保存在UserPageControlDemo文件夾下

二、創建用戶控件

在你的工程項目文件上點擊右鍵會展示出管理菜單,然后選擇添加->用戶控件

三、用戶控件開發

1.在用戶控件上拖拽你所要的其他控件,變成組合控件

2.添加App.config文件的節點,這里我們為了讓這格控件具有更好的拓展性和通用性,我們把它的每頁數據長度作成動態可配置的方式.這樣我們在不同的畫面應用這格控件的時候可以通過修改配置文件的方式進行頁面顯示數據長度的修改,而不用再去修改程序

3.ucPage開發中的技術點:

  3.1委托和事件:

在開發中我們用到了三次委托如上圖中所示的"ClickPageButton","ChangedPageSize","JumpPage"單從字面的意思就不難看出,這三個委托分別代表着"點擊分頁按鈕(如:上一頁,下一頁等)","改變頁面數據展示長度","跳轉某一頁面"。對應的是三個委托的觸發事件 這里這樣寫的目的是為了以后在頁面引用這個控件的時候可以以事件觸發的方式來實現控件或者控件上的某個子控件的某個動作的響應。這個在后面我們會講到。

  3.2控件的初始化和缺省值

這里需要初始化數據的就是頁面數據展示長度的下拉框(combobox)控件,如果我們的app.config文件中沒有配置數據長度的值,那么我們在程序內部會提供一個缺省值去彌補這個漏洞。代碼如下:其中 InitCboCtrl()方法在ucPage的構造函數中調用即可,cboPageSize控件即為Combobox控件,如圖1所示。KeyAndValueEntity類為一個自定義的內部類,是為了綁定combobox控件數據源時所用的。在實踐中可以就寫到主窗體類的下面,也可以單獨寫成一個類文件,如果寫在當前的用戶控件類下方則使用internal的訪問修飾符即可。如圖2所示。

圖1

 

 

  private void InitCboCtrl()
        {
            this.cboPageSize.ValueMember = "MValue";
            this.cboPageSize.DisplayMember = "MText";
            this.cboPageSize.Text = string.Empty;
            if (!string.IsNullOrEmpty(_cfgPageSize))
            {
                string cfgPageSize = _cfgPageSize.Replace(",", ",");
                if (cfgPageSize.EndsWith(","))
                {
                    cfgPageSize = cfgPageSize.Remove(cfgPageSize.Length - 1);
                }
                string[] strPageSize = cfgPageSize.Split(new char[] { ',' });
                List<string> listPageSize = new List<string>();
                for (int x = 0; x < strPageSize.Length; x++)
                {
                    if (!listPageSize.Contains(strPageSize[x]) && !string.IsNullOrEmpty(strPageSize[x]))
                    {
                        listPageSize.Add(strPageSize[x]);
                    }
                }
                List<KeyAndValueEntity> kve = new List<KeyAndValueEntity>();
                for (int i = 0; i < listPageSize.Count; i++)
                {
                    kve.Add(new KeyAndValueEntity() { MValue = i, MText = listPageSize[i] });
                }
                this.cboPageSize.DataSource = kve;
            }
            else
            {
                this.cboPageSize.DataSource = new List<KeyAndValueEntity>()
                {
                    new KeyAndValueEntity() {MValue = 0,MText = "10"},
                    new KeyAndValueEntity() {MValue = 1,MText = "20"},
                    new KeyAndValueEntity() {MValue = 2,MText = "50"},
                    new KeyAndValueEntity() {MValue = 3,MText = "100"}
                };
            }
            this.cboPageSize.SelectedText = cboPageSize.Items[0] as string;
        }

另附:KeyAndValueEntity類代碼

    internal class KeyAndValueEntity
    {
        public int MValue { get; set; }
        public string MText { get; set; }
    }

 從代碼中我們可以看到我們在讀取app.config文件時如果沒有獲取到動態數據,則程序會加載寫死的默認數據

  3.3構造函數與變量的聲明:

在本例中變量聲明基本上就是當前頁:CurrentPage

當前頁面展示數據長度:PageSize

當前數據總數:TotalRows

當前頁數總數:TotalPages

以及一些做展示用的相關控件和子控件:(ComboBox)CboPageSize、(Label)PageInfo、(Label)TotalRows、(TextBox)JumpPageCtrl等相關屬性或對象

這些都是為了在引用該控件的畫面調用時方便獲取和設置值、參數時使用的。

構造函數中主要是一些數據的初始化和控件的事件觸發

其中F\P\N\L分別代表着首頁、上一頁、下一頁、最后頁。他們的點擊click事件我們都用一個事件來處理,那么就要為他們的各自的Tag做標記,以此來區分按的是哪個按鈕

在最后一行處,我們可以看到我們執行了 this.ClickPageButtonEvent(this.CurrentPage);這行代碼,這里其實就是聲明委托后把事件釋放出來等待着被觸發,當然,前提是引用此空間的畫面必須要注冊這個事件,后面我們會講到。

四、引用畫面的開發

 

 直接拖拽剛才開發好的ucPage控件即可,如上圖所示,這里就不再多說DataGridView的使用了

 

這里我們能夠看到引用畫面的基本結構:

1.分頁控件的三個事件:

這里其實就是前面說的分頁控件中委托和事件的用法,如上圖引用的實例,那么在哪里去引用/注冊這些對象/事件呢?

在引用畫面的任何地方都可以,一般的,我們在引用畫面的構造函數中去引用/注冊這些對象或事件

如圖所示:

這部分就是注冊和引用ucPage的一些對象、屬性和事件。然后再在事件體中去重寫你所需要的邏輯代碼,如圖所示:

此處我們以頁面跳轉事件為例展示。

2.數據展示:

數據的展示是在一個自定義的函數(ShowDatas)中實現的。請參看代碼:

 private void ShowDatas(int currentPage)
        {
            string sql = @" SELECT t.Rn, t.TotalRows, t.Id, t.UserName, t.UserClassName, t.UserAddress
                                        FROM
                                        (
                                            SELECT COUNT(1) OVER () AS TotalRows,
                                            ROW_NUMBER() OVER (ORDER BY c.Id) AS Rn,
                                            c.Id, c.UserAddress, c.UserClassName, c.UserName
                                            FROM T_CurrentUser c
                                        ) t
                                        WHERE t.Rn BETWEEN ((" + currentPage + " - 1) * " + this.ucPageDemo.PageSize + ") + 1 AND " + currentPage + " *  " + this.ucPageDemo.PageSize;

            DataTable dtResult = DataBaseAccessOperate.GetDataTable(sql);
            int totalPages = 0;
            int totalRows = 0;
            if (null == dtResult || dtResult.Rows.Count == 0)
            {
                this.ucPageDemo.PageInfo.Text = string.Format("第{0}/{1}頁", "1", "1");
                this.ucPageDemo.TotalRows.Text = @"0";
                this.ucPageDemo.CurrentPage = 1;
                this.ucPageDemo.TotalPages = 1;
            }
            else
            {
                totalRows = Convert.ToInt32(dtResult.Rows[0]["TotalRows"].ToString());
                totalPages = totalRows % this.ucPageDemo.PageSize == 0 ? totalRows / this.ucPageDemo.PageSize : (totalRows / this.ucPageDemo.PageSize) + 1;
                this.ucPageDemo.PageInfo.Text = string.Format("第{0}/{1}頁", currentPage, totalPages);
                this.ucPageDemo.TotalRows.Text = totalRows.ToString();
                this.ucPageDemo.CurrentPage = currentPage;
                this.ucPageDemo.TotalPages = totalPages;
            }
            this.dgvDemo.DataSource = dtResult;
        }

在獲取數據集后,我們可以為ucPage控件的若干屬性賦值,具體代碼可以到第五部分 “代碼”中去參考

3.控件的初始化:

關於DataGridView的初始化本次不過多討論,可以去網上調查它的基本用法

4.運行效果:

 

 -->

 

 

 

 以上是一些運行demo時的畫面截圖。

------------------------------------------------------------------------------------------------------------分割線---------------------------------------------------------------------------------------------------------

五、代碼:

1.App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <appSettings>
        <!--分頁控件每頁顯示數據長度-->
        <!--長度多個選擇時,以","號分隔-->
        <add key="ucPageSize" value="10,20,30,50,100,200"/>
    </appSettings>
    <connectionStrings>
        <add name="DataBaseConnection" connectionString="server=your Ip Address;user id=your db id; password=your db pwd; database=your db name;"/>
    </connectionStrings>
</configuration>

2.ucPage:

  2.1 ucPage.Designer.cs:

namespace UserPageControlDemo
{
    partial class ucPage
    {
        /// <summary>
        /// 必需的設計器變量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的資源。
        /// </summary>
        /// <param name="disposing">如果應釋放托管資源,為 true;否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 組件設計器生成的代碼

        /// <summary>
        /// 設計器支持所需的方法 - 不要
        /// 使用代碼編輯器修改此方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this.btnFrist = new System.Windows.Forms.Button();
            this.lblPage = new System.Windows.Forms.Label();
            this.btnPreviou = new System.Windows.Forms.Button();
            this.btnNext = new System.Windows.Forms.Button();
            this.btnLast = new System.Windows.Forms.Button();
            this.cboPageSize = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.lblTotalRows = new System.Windows.Forms.Label();
            this.txtJumpPage = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            //
            // btnFrist
            //
            this.btnFrist.Font = new System.Drawing.Font("宋體", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.btnFrist.Location = new System.Drawing.Point(8, 5);
            this.btnFrist.Name = "btnFrist";
            this.btnFrist.Size = new System.Drawing.Size(27, 23);
            this.btnFrist.TabIndex = 0;
            this.btnFrist.Text = "<<";
            this.btnFrist.UseVisualStyleBackColor = true;
            //
            // lblPage
            //
            this.lblPage.AutoSize = true;
            this.lblPage.Font = new System.Drawing.Font("宋體", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.lblPage.Location = new System.Drawing.Point(84, 10);
            this.lblPage.Name = "lblPage";
            this.lblPage.Size = new System.Drawing.Size(52, 12);
            this.lblPage.TabIndex = 1;
            this.lblPage.Text = "第1/1頁";
            //
            // btnPreviou
            //
            this.btnPreviou.Font = new System.Drawing.Font("宋體", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.btnPreviou.Location = new System.Drawing.Point(41, 5);
            this.btnPreviou.Name = "btnPreviou";
            this.btnPreviou.Size = new System.Drawing.Size(27, 23);
            this.btnPreviou.TabIndex = 2;
            this.btnPreviou.Text = "<";
            this.btnPreviou.UseVisualStyleBackColor = true;
            //
            // btnNext
            //
            this.btnNext.Font = new System.Drawing.Font("宋體", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.btnNext.Location = new System.Drawing.Point(152, 5);
            this.btnNext.Name = "btnNext";
            this.btnNext.Size = new System.Drawing.Size(27, 23);
            this.btnNext.TabIndex = 3;
            this.btnNext.Text = ">";
            this.btnNext.UseVisualStyleBackColor = true;
            //
            // btnLast
            //
            this.btnLast.Font = new System.Drawing.Font("宋體", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.btnLast.Location = new System.Drawing.Point(185, 5);
            this.btnLast.Name = "btnLast";
            this.btnLast.Size = new System.Drawing.Size(27, 23);
            this.btnLast.TabIndex = 4;
            this.btnLast.Text = ">>";
            this.btnLast.UseVisualStyleBackColor = true;
            //
            // cboPageSize
            //
            this.cboPageSize.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.cboPageSize.FormattingEnabled = true;
            this.cboPageSize.Location = new System.Drawing.Point(347, 7);
            this.cboPageSize.Name = "cboPageSize";
            this.cboPageSize.Size = new System.Drawing.Size(46, 20);
            this.cboPageSize.TabIndex = 5;
            //
            // label1
            //
            this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("宋體", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label1.Location = new System.Drawing.Point(314, 10);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(31, 12);
            this.label1.TabIndex = 6;
            this.label1.Text = "每頁";
            //
            // label2
            //
            this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("宋體", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label2.Location = new System.Drawing.Point(397, 10);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(18, 12);
            this.label2.TabIndex = 7;
            this.label2.Text = "條";
            //
            // label3
            //
            this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("宋體", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label3.Location = new System.Drawing.Point(432, 10);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(18, 12);
            this.label3.TabIndex = 8;
            this.label3.Text = "共";
            //
            // label4
            //
            this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("宋體", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label4.Location = new System.Drawing.Point(489, 10);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(18, 12);
            this.label4.TabIndex = 9;
            this.label4.Text = "條";
            //
            // lblTotalRows
            //
            this.lblTotalRows.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.lblTotalRows.AutoSize = true;
            this.lblTotalRows.Font = new System.Drawing.Font("宋體", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.lblTotalRows.Location = new System.Drawing.Point(456, 10);
            this.lblTotalRows.Name = "lblTotalRows";
            this.lblTotalRows.Size = new System.Drawing.Size(12, 12);
            this.lblTotalRows.TabIndex = 10;
            this.lblTotalRows.Text = "0";
            //
            // txtJumpPage
            //
            this.txtJumpPage.Location = new System.Drawing.Point(240, 5);
            this.txtJumpPage.Multiline = true;
            this.txtJumpPage.Name = "txtJumpPage";
            this.txtJumpPage.Size = new System.Drawing.Size(30, 21);
            this.txtJumpPage.TabIndex = 11;
            //
            // ucPage
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.txtJumpPage);
            this.Controls.Add(this.lblTotalRows);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.cboPageSize);
            this.Controls.Add(this.btnLast);
            this.Controls.Add(this.btnNext);
            this.Controls.Add(this.btnPreviou);
            this.Controls.Add(this.lblPage);
            this.Controls.Add(this.btnFrist);
            this.Name = "ucPage";
            this.Size = new System.Drawing.Size(520, 31);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnFrist;
        private System.Windows.Forms.Label lblPage;
        private System.Windows.Forms.Button btnPreviou;
        private System.Windows.Forms.Button btnNext;
        private System.Windows.Forms.Button btnLast;
        private System.Windows.Forms.ComboBox cboPageSize;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label lblTotalRows;
        private System.Windows.Forms.TextBox txtJumpPage;
    }
}
2.2ucPage.cs:

namespace UserPageControlDemo
{
    public partial class ucPage : UserControl
    {
        private string _cfgPageSize = ConfigurationManager.AppSettings["ucPageSize"];

        public delegate void ClickPageButton(int current);
        public event ClickPageButton ClickPageButtonEvent;

        public delegate void ChangedPageSize();
        public event ChangedPageSize ChangedPageSizeEvent;

        public delegate void JumpPage(int jumpPage);
        public event JumpPage JumpPageEvent;

        public int TotalPages { get; set; }

        private int currentPage;
        public int CurrentPage
        {
            get { return this.currentPage; }
            set { this.currentPage = value; }
        }

        private int pageSize;
        public int PageSize
        {
            get { return this.pageSize; }
            set { this.pageSize = value; }
        }

        public ComboBox CboPageSize
        {
            set { this.cboPageSize = value; }
            get { return this.cboPageSize; }
        }

        public Label PageInfo
        {
            set { this.lblPage = value; }
            get { return this.lblPage; }
        }

        public Label TotalRows
        {
            get { return this.lblTotalRows; }
            set { this.lblTotalRows = value; }
        }

        public TextBox JumpPageCtrl
        {
            get { return this.txtJumpPage; }
            set { this.txtJumpPage = value; }
        }

        public ucPage()
        {
            InitializeComponent();
            this.InitCboCtrl();
            this.cboPageSize.TextChanged += cboPageSize_TextChanged;
            this.cboPageSize.KeyPress += cboPageSize_KeyPress;
            this.btnFrist.Tag = "F";
            this.btnPreviou.Tag = "P";
            this.btnNext.Tag = "N";
            this.btnLast.Tag = "L";
            this.btnFrist.Click += btn_Click;
            this.btnPreviou.Click += btn_Click;
            this.btnNext.Click += btn_Click;
            this.btnLast.Click += btn_Click;
            this.cboPageSize.KeyPress += cboPageSize_KeyPress;
            this.txtJumpPage.KeyPress += txtJumpPage_KeyPress;
        }

        void txtJumpPage_KeyPress(object sender, KeyPressEventArgs e)
        {
            //text輸入驗證
            if (e.KeyChar == 13)
            {
                if (null != this.JumpPageEvent)
                {
                    this.JumpPageEvent(Convert.ToInt32(this.txtJumpPage.Text));
                }
            }
            else
            {
                if (e.KeyChar != 8)
                {
                    int len = this.txtJumpPage.Text.Length;
                    if (len < 1 && e.KeyChar == '0')
                    {
                        e.Handled = true;
                    }
                    else if ((e.KeyChar < '0') || (e.KeyChar > '9'))//這是允許輸入0-9數字
                    {
                        e.Handled = true;
                    }
                }
            }
        }
        void btn_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            if (null != this.ClickPageButtonEvent)
            {
                if (null != btn)
                {
                    switch (btn.Tag.ToString())
                    {
                        case "F":
                            this.CurrentPage = 1;
                            break;
                        case "P":
                            this.CurrentPage = this.CurrentPage <= 1 ? 1 : this.CurrentPage - 1;
                            break;
                        case "N":
                            this.CurrentPage = this.CurrentPage + 1;
                            break;
                        case "L":
                            this.CurrentPage = this.TotalPages;
                            break;
                        default:
                            this.CurrentPage = 1;
                            break;
                    }
                    this.ClickPageButtonEvent(this.CurrentPage);
                }
            }
        }
        void cboPageSize_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
        }
        void cboPageSize_TextChanged(object sender, EventArgs e)
        {
            this.PageSize = Convert.ToInt32(this.cboPageSize.Text);
            if (null != ChangedPageSizeEvent)
            {
                this.ChangedPageSizeEvent();
            }
        }
        private void InitCboCtrl()
        {
            this.cboPageSize.ValueMember = "MValue";
            this.cboPageSize.DisplayMember = "MText";
            this.cboPageSize.Text = string.Empty;
            if (!string.IsNullOrEmpty(_cfgPageSize))
            {
                string cfgPageSize = _cfgPageSize.Replace(",", ",");
                if (cfgPageSize.EndsWith(","))
                {
                    cfgPageSize = cfgPageSize.Remove(cfgPageSize.Length - 1);
                }
                string[] strPageSize = cfgPageSize.Split(new char[] { ',' });
                List<string> listPageSize = new List<string>();
                for (int x = 0; x < strPageSize.Length; x++)
                {
                    if (!listPageSize.Contains(strPageSize[x]) && !string.IsNullOrEmpty(strPageSize[x]))
                    {
                        listPageSize.Add(strPageSize[x]);
                    }
                }
                List<KeyAndValueEntity> kve = new List<KeyAndValueEntity>();
                for (int i = 0; i < listPageSize.Count; i++)
                {
                    kve.Add(new KeyAndValueEntity() { MValue = i, MText = listPageSize[i] });
                }
                this.cboPageSize.DataSource = kve;
            }
            else
            {
                this.cboPageSize.DataSource = new List<KeyAndValueEntity>()
                {
                    new KeyAndValueEntity() {MValue = 0,MText = "10"},
                    new KeyAndValueEntity() {MValue = 1,MText = "20"},
                    new KeyAndValueEntity() {MValue = 2,MText = "50"},
                    new KeyAndValueEntity() {MValue = 3,MText = "100"}
                };
            }
            this.cboPageSize.SelectedText = cboPageSize.Items[0] as string;
        }
    }

    internal class KeyAndValueEntity
    {
        public int MValue { get; set; }
        public string MText { get; set; }
    }
}

2.3 引用畫面:

    public partial class FrmPageDemo : Form
    {
        public FrmPageDemo()
        {
            InitializeComponent();
            this.ucPageDemo.CurrentPage = 1;
            this.ucPageDemo.PageSize = Convert.ToInt32(this.ucPageDemo.CboPageSize.Text);
            this.ucPageDemo.TotalPages = 1;
            this.ucPageDemo.ClickPageButtonEvent += ucPageDemo_ClickPageButtonEvent;
            this.ucPageDemo.ChangedPageSizeEvent += ucPageDemo_ChangedPageSizeEvent;
            this.ucPageDemo.JumpPageEvent += ucPageDemo_JumpPageEvent;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.InitDataGridViewCtrl();
        }
        /// <summary>
        /// 頁數跳轉
        /// </summary>
        /// <param name="jumpPage">跳轉頁</param>
        void ucPageDemo_JumpPageEvent(int jumpPage)
        {
            if (jumpPage <= this.ucPageDemo.TotalPages)
            {
                if (jumpPage > 0)
                {
                    this.ucPageDemo.JumpPageCtrl.Text = string.Empty;
                    this.ucPageDemo.JumpPageCtrl.Text = jumpPage.ToString();
                    this.ShowDatas(jumpPage);
                }
                else
                {
                    jumpPage = 1;
                    this.ucPageDemo.JumpPageCtrl.Text = string.Empty;
                    this.ucPageDemo.JumpPageCtrl.Text = jumpPage.ToString();
                    this.ShowDatas(jumpPage);
                }
            }
            else
            {
                this.ucPageDemo.JumpPageCtrl.Text = string.Empty;
                MessageBox.Show(@"超出當前最大頁數", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// 改變每頁展示數據長度
        /// </summary>
        void ucPageDemo_ChangedPageSizeEvent()
        {
            this.ShowDatas(1);
        }
        /// <summary>
        /// 頁數改變按鈕(最前頁,最后頁,上一頁,下一頁)
        /// </summary>
        /// <param name="current"></param>
        void ucPageDemo_ClickPageButtonEvent(int current)
        {
            this.ShowDatas(current);
        }
        /// <summary>
        /// 初始化DataGridView控件
        /// </summary>
        private void InitDataGridViewCtrl()
        {
            this.ShowDatas(1);
        }
        /// <summary>
        /// 數據展示
        /// </summary>
        /// <param name="currentPage">當前頁</param>
        private void ShowDatas(int currentPage)
        {
            string sql = @" SELECT t.Rn, t.TotalRows, t.Id, t.UserName, t.UserClassName, t.UserAddress
                                        FROM
                                        (
                                            SELECT COUNT(1) OVER () AS TotalRows,
                                            ROW_NUMBER() OVER (ORDER BY c.Id) AS Rn,
                                            c.Id, c.UserAddress, c.UserClassName, c.UserName
                                            FROM T_CurrentUser c
                                        ) t
                                        WHERE t.Rn BETWEEN ((" + currentPage + " - 1) * " + this.ucPageDemo.PageSize + ") + 1 AND " + currentPage + " *  " + this.ucPageDemo.PageSize;

            DataTable dtResult = DataBaseAccessOperate.GetDataTable(sql);
            int totalPages = 0;
            int totalRows = 0;
            if (null == dtResult || dtResult.Rows.Count == 0)
            {
                this.ucPageDemo.PageInfo.Text = string.Format("第{0}/{1}頁", "1", "1");
                this.ucPageDemo.TotalRows.Text = @"0";
                this.ucPageDemo.CurrentPage = 1;
                this.ucPageDemo.TotalPages = 1;
            }
            else
            {
                totalRows = Convert.ToInt32(dtResult.Rows[0]["TotalRows"].ToString());
                totalPages = totalRows % this.ucPageDemo.PageSize == 0 ? totalRows / this.ucPageDemo.PageSize : (totalRows / this.ucPageDemo.PageSize) + 1;
                this.ucPageDemo.PageInfo.Text = string.Format("第{0}/{1}頁", currentPage, totalPages);
                this.ucPageDemo.TotalRows.Text = totalRows.ToString();
                this.ucPageDemo.CurrentPage = currentPage;
                this.ucPageDemo.TotalPages = totalPages;
            }
            this.dgvDemo.DataSource = dtResult;
        }
    }

 

以上

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM