C# WinForm自定义通用分页控件

C# WinForm自定义通用分页控件

大家好,前几天因工作需要要开发一个基于WinForm的小程序。其中要用到分页,最开始的想法找个第三方的dll用一下,但是后来想了想觉得不如自己写一个玩一下 之前的web开发中有各式各样的列表组件基本都带有分页功能,笔者早先也自己写过B/S端的分页组件(利用jquery纯前端方式)。对于WinForm的还是第一次。当完成后发现其实要比B/S端的简单,基本上都是基于各种控件的事件和委托来实现的。后面会介绍到委托和事件在自定义组合用户控件中的使用。

一、创建一个WinForm项目,我用的是VS2013 基本上VS其他版本都差不多一样

创建一个WinForm项目
建立一个名字叫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
在这里插入图片描述
图2

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 listPageSize = new List();
for (int x = 0; x < strPageSize.Length; x++)
{
if (!listPageSize.Contains(strPageSize[x]) && !string.IsNullOrEmpty(strPageSize[x]))
{
listPageSize.Add(strPageSize[x]);
}
}
List kve = new List();
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()
{
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" ?>

2.ucPage:

2.1 ucPage.Designer.cs:

namespace UserPageControlDemo
{
partial class ucPage
{
///
/// 必需的设计器变量。
///
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;
    }
}

以上

一、AspNetPager支持两种方式分页: 一种是PostBack方式分页, 一种是通过Url来实现分页以及Url重写功能 二、AspNetPager支持各种数据绑定控件GridView、DataGrid、DataList、Repeater以及自定义的数据绑定控件分页功能十分强大。 三、AspNetPager分页控件本身并不显示任何数据,而只显示分页导航元素,数据在页面上的显示方式与该控件无关,所以需要手写数据连接方法来配合, 四、结合TOP 。。。NOT IN 的通用存储过程分页方法使用AspNetPager十分实用 测试控件datalist aspnetpager 的分页方法示例 分页方法为 PostBack 方式 1、 首先将AspNetPager.dll复制于应用程序下的bin目录,打开解决方案,引入dll文件 2、 在工具栏中添加控件,这样可以支持拖拽使用 3、 要使用AspNetPager 要为其设置最基本的属性 使用 SqlServer Northwind数据库的 Products表 protected Wuqi.Webdiyer.AspNetPager AspNetPager1; protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.DataList DataList1; private void Page_Load(object sender, System.EventArgs e) { this.AspNetPager1.PageSize=10; //设置每也显示的记录条数 if(!IsPostBack) //只在页面第一次加载时起作用 { SqlDBManager db = new SqlDBManager(System.Configuration.ConfigurationSettings.AppSettings["SqlConnectionString"]); AspNetPager1.RecordCount=db.CountPage("products");//获得要使用表的记录总数 //db.CountItems自定义的方法 this.BindData(); } } private void BindData() { SqlDBManager db= new SqlDBManager(System.Configuration.ConfigurationSettings.AppSettings["SqlConnectionString"].ToString(); DataList1.DataSource=db.FenPage(this.AspNetPager1.PageSize,this.AspNetPager1.CurrentPageIndex,"productid","products","productid,productname,unitprice,unitsinstock",""); //自定义方法由 TOP not in 存储过程分页方法改编 this.DataList1.DataBind(); //控件数据绑定 this.Label1.Text="当前第"+this.AspNetPager1.CurrentPageIndex+"页 总"+this.AspNetPager1.PageCount+"页"; } private void AspNetPager1_PageChanged(object sender, System.EventArgs e) { //页索引改变方法 this.BindData(); } 设计页效果 <asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 296px; POSITION: absolute; TOP: 96px" runat="server"> <HeaderTemplate> <table border='1'> <tr> <td>产品ID</td> <td>产品名称</td> <td>产品数量</td> <td>产品单价</td> </tr> </HeaderTemplate> <FooterTemplate> </table> </FooterTemplate> <ItemTemplate> <tr> <td><%# DataBinder.Eval(Container.DataItem,"Productid")%></td> <td><%# DataBinder.Eval(Container.DataItem,"productname")%></td> <td><%# DataBinder.Eval(Container.DataItem,"unitprice")%></td> <td><%# DataBinder.Eval(Container.DataItem,"unitsinstock")%></td> </tr> </ItemTemplate> </asp:DataList> <webdiyer:AspNetPager id="AspNetPager1" style="Z-INDEX: 102; LEFT: 256px; POSITION: absolute; TOP: 40px" runat="server" Width="500px" FirstPageText="首页" LastPageText="尾页" NextPageText="下一页" PrevPageText="上一页" Height="40px" NumericButt PagingButt ShowNavigati ShowInputBox="Always" TextAfterInputBox="页" TextBeforeInputBox="跳转到第" AlwaysShow="True"> </webdiyer:AspNetPager> <asp:Label id="Label1" style="Z-INDEX: 103; LEFT: 120px; POSITION: absolute; TOP: 56px" runat="server">Label</asp:Label>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值