分享一个Winform下的分页控件

本文介绍了在Winform环境下如何使用一个分页控件,并提供了简化后的分页存储过程代码,以及C# WinForm项目的测试源码。通过示例展示了如何绑定数据、设置总记录数和翻页事件。
摘要由CSDN通过智能技术生成

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

前两天有一个简单的C/S项目用到分页,因为是Winform下,没有现成的,自己也懒得写,就找了下,看到了ycmoon的一个控件

http://www.cnblogs.com/ycmoon/archive/2010/01/07/1640689.html

参考后,做了简化,只保留了分页的部分,主要是点击事件的Delegate,未做过多测试,有兴趣的朋友可以下载源码自行修改,如有好的建议,也可以给我反馈。3w@live.cn,效果如下:

控件设计界面:

邀月工作室

设计时:

邀月工作室

运行时:

邀月工作室

附带一个取分页数据的存储过程:

  1. Create DataBase Db_TonyPaging  
  2. go  
  3. use Db_TonyPaging  
  4. go  
  5. if exists (select 1  
  6.             from  sysobjects  
  7.            where  id = object_id('DepartDemo')  
  8.             and   type = 'U')  
  9.    drop table DepartDemo  
  10. go  
  11. /*==============================================================*/  
  12. /* Table: DepartDemo                                            */  
  13. /*==============================================================*/  
  14. create table DepartDemo (  
  15.    PKID                 int                  identity(1,1),  
  16.    DName                nvarchar(200)        null,  
  17.    DCode                nvarchar(500)        null,  
  18.    Manager              nvarchar(50)         null,  
  19.    ParentID             int                  null default 0,  
  20.    AddUser              nvarchar(50)         null,  
  21.    AddTime              datetime             null,  
  22.    ModUser              nvarchar(50)         null,  
  23.    ModTime              datetime             null,  
  24.    CurState             smallint             not null default 0,  
  25.    Remark               nvarchar(500)        null,  
  26.    F1                   int                  not null default 0,  
  27.    F2                   nvarchar(300)        null,  
  28.    constraint PK_DEPARTDEMO primary key (PKID)  
  29. )  
  30. go  
  31. truncate table DepartDemo  
  32. go  
  33. /***************创建54 条测试数据*********************  
  34. ****************downmoo  3w@live.cn ***************/  
  35. declare @d datetime   
  36. set @d=getdate()   
  37. declare @i int  
  38. set @i=1  
  39. while @i<=54  
  40. begin  
  41.     --插入一条测试数据  
  42.     insert into DepartDemo  
  43.     select '国家统计局房产审计'+Cast(@i as Nvarchar(10))+'科','0','胡不归',0,'DemoUser',getdate(),  
  44.     '','1900-01-01',1,'专业评估全国房价,为老百姓谋福祉',0,''  
  45.     set @i=@i+1  
  46. end  
  47. go  
  48. --***********分页存储过程用于SQL server2005/2008、2008R2****************************  
  49. SET ANSI_NULLS ON  
  50. GO  
  51. SET QUOTED_IDENTIFIER ON  
  52. GO  
  53. Create PROCEDURE [dbo].[ZJF_CPP_GetPagedRecordFor2005_2008]  
  54. (@Table varchar(1000), --表名,多表是请使用 tA a inner join tB b On a.AID = b.AID  
  55. @TIndex nvarchar(100),    --主键,可以带表头 a.AID  
  56. @Column nvarchar(2000) = '*',--读取字段  
  57. @Sql nvarchar(3000) = '',--Where条件  
  58. @PageIndex int = 1,    --开始页码  
  59. @PageSize int = 10,        --页大小  
  60. @Sort nvarchar(200) = '' --排序字段  
  61. )  
  62. AS  
  63. DECLARE @strWhere varchar(2000)  
  64. declare @strsql nvarchar(3900)  
  65. IF @Sql IS NOT NULL AND len(ltrim(rtrim(@Sql)))>0  
  66.   BEGIN  
  67.    SET @strWhere = ' WHERE ' + @Sql + ' '  
  68.   END  
  69. ELSE  
  70.   BEGIN  
  71.    SET @strWhere = ''  
  72.   END  
  73.           
  74. if (charindex(ltrim(rtrim(@TIndex)),@Sort)=0)  
  75. begin  
  76.     if(@Sort='')  
  77.         set @Sort = @TIndex + ' DESC '  
  78.     else  
  79.         set @Sort = @Sort' , '+@TIndex + ' DESC '  
  80. end  
  81. IF @PageIndex < 1  
  82.   SET @PageIndex = 1  
  83.         if @PageIndex = 1 --第一页提高性能  
  84.         begin   
  85.           set @strsql = 'select top ' + str(@PageSize) +' '+@Column'  from ' + @Table + ' ' + @strWhere + ' ORDER BY  '@Sort  
  86.         end   
  87.         else  
  88.           begin  
  89.           /**//**//**//*Execute dynamic query*/      
  90.             DECLARE @START_ID nvarchar(50)  
  91.             DECLARE @END_ID nvarchar(50)  
  92.             SET @START_ID = convert(nvarchar(50),(@PageIndex - 1) * @PageSize + 1)  
  93.             SET @END_ID = convert(nvarchar(50),@PageIndex * @PageSize)  
  94.             set @strsql =  ' SELECT '+@Column+ '  
  95.            FROM (SELECT ROW_NUMBER() OVER(ORDER BY '+@Sort+') AS rownum,   
  96.              '+@Column+ '  
  97.               FROM '+@Table +' WITH(NOLOCK) ' + @strWhere +') AS D  
  98.            WHERE rownum BETWEEN '+@START_ID+' AND ' +@END_ID +' ORDER BY '+@Sort  
  99.           END  
  100. EXEC(@strsql)  
  101. print @strsql  
  102.     set @strsql = 'SELECT  Count(1) as TotalRecords FROM ' + @Table +' WITH(NOLOCK) ' + @strWhere    
  103. print @strsql  
  104. EXEC(@strsql)  
Create DataBase Db_TonyPaginggouse Db_TonyPaginggoif exists (select 1            from  sysobjects           where  id = object_id('DepartDemo')            and   type = 'U')   drop table DepartDemogo/*==============================================================*//* Table: DepartDemo                                            *//*==============================================================*/create table DepartDemo (   PKID                 int                  identity(1,1),   DName                nvarchar(200)        null,   DCode                nvarchar(500)        null,   Manager              nvarchar(50)         null,   ParentID             int                  null default 0,   AddUser              nvarchar(50)         null,   AddTime              datetime             null,   ModUser              nvarchar(50)         null,   ModTime              datetime             null,   CurState             smallint             not null default 0,   Remark               nvarchar(500)        null,   F1                   int                  not null default 0,   F2                   nvarchar(300)        null,   constraint PK_DEPARTDEMO primary key (PKID))gotruncate table DepartDemogo/***************创建54 条测试数据*************************************downmoo  3w@live.cn ***************/declare @d datetime set @d=getdate() declare @i intset @i=1while @i<=54begin    --插入一条测试数据    insert into DepartDemo    select '国家统计局房产审计'+Cast(@i as Nvarchar(10))+'科','0','胡不归',0,'DemoUser',getdate(),    '','1900-01-01',1,'专业评估全国房价,为老百姓谋福祉',0,''    set @i=@i+1endgo--***********分页存储过程用于SQL server2005/2008、2008R2****************************SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCreate PROCEDURE [dbo].[ZJF_CPP_GetPagedRecordFor2005_2008](@Table varchar(1000), --表名,多表是请使用 tA a inner join tB b On a.AID = b.AID@TIndex nvarchar(100),    --主键,可以带表头 a.AID@Column nvarchar(2000) = '*',--读取字段@Sql nvarchar(3000) = '',--Where条件@PageIndex int = 1,    --开始页码@PageSize int = 10,        --页大小@Sort nvarchar(200) = '' --排序字段)ASDECLARE @strWhere varchar(2000)declare @strsql nvarchar(3900)IF @Sql IS NOT NULL AND len(ltrim(rtrim(@Sql)))>0  BEGIN   SET @strWhere = ' WHERE ' + @Sql + ' '  ENDELSE  BEGIN   SET @strWhere = ''  END        if (charindex(ltrim(rtrim(@TIndex)),@Sort)=0)begin    if(@Sort='')        set @Sort = @TIndex + ' DESC '    else        set @Sort = @Sort+ ' , '+@TIndex + ' DESC 'endIF @PageIndex < 1  SET @PageIndex = 1        if @PageIndex = 1 --第一页提高性能        begin           set @strsql = 'select top ' + str(@PageSize) +' '+@Column+ '  from ' + @Table + ' ' + @strWhere + ' ORDER BY  '+ @Sort        end         else          begin          /**//**//**//*Execute dynamic query*/                DECLARE @START_ID nvarchar(50)            DECLARE @END_ID nvarchar(50)            SET @START_ID = convert(nvarchar(50),(@PageIndex - 1) * @PageSize + 1)            SET @END_ID = convert(nvarchar(50),@PageIndex * @PageSize)            set @strsql =  ' SELECT '+@Column+ '           FROM (SELECT ROW_NUMBER() OVER(ORDER BY '+@Sort+') AS rownum,              '+@Column+ '              FROM '+@Table +' WITH(NOLOCK) ' + @strWhere +') AS D           WHERE rownum BETWEEN '+@START_ID+' AND ' +@END_ID +' ORDER BY '+@Sort          ENDEXEC(@strsql)print @strsql    set @strsql = 'SELECT  Count(1) as TotalRecords FROM ' + @Table +' WITH(NOLOCK) ' + @strWhere  print @strsqlEXEC(@strsql)

 

在WinForm项目中,需要设置控件的总记录数RecordCount(由分页存储过程计算得出),和翻页事件winFormPager1_PageIndexChanged。

邀月工作室

邀月工作室

邀月工作室

测试源码如下:

 

[c-sharp] view plain copy print ?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8. using System.Data.SqlClient;  
  9. namespace DemoPager  
  10. {  
  11.     public partial class frmMain : Form  
  12.     {  
  13.         public frmMain()  
  14.         {  
  15.             InitializeComponent();  
  16.         }  
  17.         #region Members  
  18.         //总记录数  
  19.         public int RecordCount = 0;  
  20.         private string strConn = @"Data Source=ap2/vegnet;Initial Catalog=Db_TonyPaging;Integrated Security=SSPI;";  
  21.         //"Server=localhost;database=Db_TonyPaging;uid=sa;pwd=sa;";  
  22.         private string strProcedure = "ZJF_CPP_GetPagedRecordFor2005_2008";  
  23.         #endregion  
  24.         #region Methods  
  25.         /// <summary>  
  26.         /// 绑定第Index页的数据  
  27.         /// </summary>  
  28.         /// <param name="Index"></param>  
  29.         private void BindDataWithPage(int Index)  
  30.         {  
  31.             winFormPager1.PageIndex = Index;  
  32.             //winFormPager1.PageSize = 10;; ;  
  33.             dgvList.DataSource = GetData(strConn, strProcedure, Index, winFormPager1.PageSize);  
  34.             //获取并设置总记录数  
  35.             winFormPager1.RecordCount = RecordCount;  
  36.         }  
  37.         /// <summary>  
  38.         /// 获取数据源  
  39.         /// </summary>  
  40.         /// <param name="conn"></param>  
  41.         /// <param name="strProcedure"></param>  
  42.         /// <param name="pageIndex"></param>  
  43.         /// <param name="pageSize"></param>  
  44.         /// <returns></returns>  
  45.         private DataTable GetData(string conn, string strProcedure, int pageIndex, int pageSize)  
  46.         {  
  47.             using (SqlConnection connection = new SqlConnection(conn))  
  48.             {  
  49.                 SqlCommand command = new SqlCommand(strProcedure, connection);  
  50.                 command.CommandType = CommandType.StoredProcedure;//采用存储过程  
  51.                 //存储过程参数  
  52.                 command.Parameters.Add("@Table", SqlDbType.NVarChar, 1000).Value = "DepartDemo";  
  53.                 command.Parameters.Add("@TIndex", SqlDbType.NVarChar, 100).Value = "PKID";  
  54.                 command.Parameters.Add("@Column", SqlDbType.NVarChar, 2000).Value = "*";  
  55.                 command.Parameters.Add("@Sql", SqlDbType.NVarChar, 3000).Value = " 1=1 ";  
  56.                 command.Parameters.Add("@PageIndex", SqlDbType.Int, 8).Value = pageIndex.ToString();  
  57.                 command.Parameters.Add("@PageSize", SqlDbType.Int, 8).Value = pageSize.ToString();  
  58.                 command.Parameters.Add("@Sort", SqlDbType.NVarChar, 200).Value = " PKID desc";  
  59.                 //打开连接  
  60.                 if (connection.State != ConnectionState.Open) { connection.Open(); }  
  61.                 try  
  62.                 {  
  63.                     //填充数据  
  64.                     SqlDataAdapter da = new SqlDataAdapter(command);  
  65.                     DataSet ds = new DataSet();  
  66.                     da.Fill(ds);  
  67.                     //获取总记录数  
  68.                     RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);  
  69.                     //返回数据集  
  70.                     return ds.Tables[0];  
  71.                 }  
  72.                 catch (SqlException err)  
  73.                 {  
  74.                     MessageBox.Show(err.Message);  
  75.                     return null; ;  
  76.                 }  
  77.                 finally  
  78.                 {  
  79.                     connection.Close();  
  80.                 }  
  81.             }  
  82.         }  
  83.         #endregion  
  84.         #region Events  
  85.         private void frmMain_Load(object sender, EventArgs e)  
  86.         {  
  87.             //不自动生成列  
  88.             dgvList.AutoGenerateColumns = false;  
  89.             //绑定数据  
  90.             BindDataWithPage(1);  
  91.         }  
  92.         /// <summary>  
  93.         /// 翻页事件  
  94.         /// </summary>  
  95.         /// <param name="sender"></param>  
  96.         /// <param name="e"></param>  
  97.         private void winFormPager1_PageIndexChanged(object sender, EventArgs e)  
  98.         {  
  99.             BindDataWithPage(winFormPager1.PageIndex);  
  100.         }  
  101.         #endregion  
  102.     }  
  103. }  
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Data.SqlClient;namespace DemoPager{    public partial class frmMain : Form    {        public frmMain()        {            InitializeComponent();        }        #region Members        //总记录数        public int RecordCount = 0;        private string strConn = @"Data Source=ap2/vegnet;Initial Catalog=Db_TonyPaging;Integrated Security=SSPI;";        //"Server=localhost;database=Db_TonyPaging;uid=sa;pwd=sa;";        private string strProcedure = "ZJF_CPP_GetPagedRecordFor2005_2008";        #endregion        #region Methods        /// <summary>        /// 绑定第Index页的数据        /// </summary>        /// <param name="Index"></param>        private void BindDataWithPage(int Index)        {            winFormPager1.PageIndex = Index;            //winFormPager1.PageSize = 10;; ;            dgvList.DataSource = GetData(strConn, strProcedure, Index, winFormPager1.PageSize);            //获取并设置总记录数            winFormPager1.RecordCount = RecordCount;        }        /// <summary>        /// 获取数据源        /// </summary>        /// <param name="conn"></param>        /// <param name="strProcedure"></param>        /// <param name="pageIndex"></param>        /// <param name="pageSize"></param>        /// <returns></returns>        private DataTable GetData(string conn, string strProcedure, int pageIndex, int pageSize)        {            using (SqlConnection connection = new SqlConnection(conn))            {                SqlCommand command = new SqlCommand(strProcedure, connection);                command.CommandType = CommandType.StoredProcedure;//采用存储过程                //存储过程参数                command.Parameters.Add("@Table", SqlDbType.NVarChar, 1000).Value = "DepartDemo";                command.Parameters.Add("@TIndex", SqlDbType.NVarChar, 100).Value = "PKID";                command.Parameters.Add("@Column", SqlDbType.NVarChar, 2000).Value = "*";                command.Parameters.Add("@Sql", SqlDbType.NVarChar, 3000).Value = " 1=1 ";                command.Parameters.Add("@PageIndex", SqlDbType.Int, 8).Value = pageIndex.ToString();                command.Parameters.Add("@PageSize", SqlDbType.Int, 8).Value = pageSize.ToString();                command.Parameters.Add("@Sort", SqlDbType.NVarChar, 200).Value = " PKID desc";                //打开连接                if (connection.State != ConnectionState.Open) { connection.Open(); }                try                {                    //填充数据                    SqlDataAdapter da = new SqlDataAdapter(command);                    DataSet ds = new DataSet();                    da.Fill(ds);                    //获取总记录数                    RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);                    //返回数据集                    return ds.Tables[0];                }                catch (SqlException err)                {                    MessageBox.Show(err.Message);                    return null; ;                }                finally                {                    connection.Close();                }            }        }        #endregion        #region Events        private void frmMain_Load(object sender, EventArgs e)        {            //不自动生成列            dgvList.AutoGenerateColumns = false;            //绑定数据            BindDataWithPage(1);        }        /// <summary>        /// 翻页事件        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void winFormPager1_PageIndexChanged(object sender, EventArgs e)        {            BindDataWithPage(winFormPager1.PageIndex);        }        #endregion    }}

 

下载控件源码及演示程序(含SQL)


下载地址二

下载地址一

 

邀月注:本文版权由邀月和CSDN共同所有,转载请注明出处。助人等于自助!   3w@live.cn
           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow
这里写图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值