1.建立用户控件Pager.ascx

1.1 html

<script language="javascript">    
    function callButtonEvent()
    {
        var keycode =window.event.keyCode;
        if(keycode==13)
        {
            if(check()==true)
            {
                event.cancelBubble=true;
                event.returnValue=false;
                document.getElementById('<%=btnGo.ClientID%>').click();
            }
        }
    }
    function check()
    {
        var count =  parseInt(document.getElementById('<%=lblTotal.ClientID%>').outerText);
        var txt = document.getElementById('<%=txtCurrentPage.ClientID%>').value;
        var cur = parseInt(txt);
        if ((cur | NaN) ==0)
        {
            alert('Input page must format as integer.');            
            event.cancelPostBack=true;            
            return false;
        }
        if (cur > count || cur < 1)
        {
            alert('Input page no out of range.');            
            event.cancelPostBack=true;
            return false;
        }
    }
</script>
<TABLE ID="Table1" CELLSPACING="0" CELLPADDING="0" WIDTH="100%" BORDER="0">
    <colgroup>
        <col width="400">
        <col width="50">
        <col width="50">
        <col width="40">
        <col width="20">
        <col width="40">
        <col width="40">
        <col width="50">
        <col width="70">
    </colgroup>
    <TR align="right">
        <td></td>
        <TD><asp:LinkButton id="btnFirstPage" runat="server" CommandArgument="First">第一页</asp:LinkButton></TD>
        <TD><asp:LinkButton id="btnPrevPage" runat="server" CommandArgument="Prev">上一页</asp:LinkButton></TD>
        <TD><ASP:TEXTBOX ID="txtCurrentPage" RUNAT="server" MAXLENGTH="3" Width="40">0</ASP:TEXTBOX></TD>
        <TD><ASP:LABEL ID="labOf" RUNAT="server">of</ASP:LABEL></TD>
        <TD><ASP:LABEL ID="lblTotal" RUNAT="server">0</ASP:LABEL></TD>
        <TD><ASP:BUTTON ID="btnGo" RUNAT="server" TEXT="转到" COMMANDARGUMENT="Go" ToolTip="转到"></ASP:BUTTON></TD>
        <TD><asp:LinkButton id="btnNextPage" runat="server" CommandArgument="Next">下一页</asp:LinkButton></TD>
        <TD><asp:LinkButton id="btnLastPage" runat="server" CommandArgument="Last">最后一页</asp:LinkButton></TD>
    </TR>
</TABLE>

1.2 cs代码

public class Pager : System.Web.UI.UserControl
    {
        protected System.Web.UI.WebControls.Label lblTotal;
        protected System.Web.UI.WebControls.Label labOf;
        protected System.Web.UI.WebControls.TextBox txtCurrentPage;
        protected System.Web.UI.WebControls.Button btnGo;
        protected System.Web.UI.WebControls.LinkButton btnFirstPage;
        protected System.Web.UI.WebControls.LinkButton btnPrevPage;
        protected System.Web.UI.WebControls.LinkButton btnNextPage;
        protected System.Web.UI.WebControls.LinkButton btnLastPage;
        int size=10;//可以在web.config中配置
        public event System.EventHandler NavigationClick;

        private void Page_Load(object sender, System.EventArgs e)
        {    
            this.txtCurrentPage.Attributes.Add("onkeypress","callButtonEvent();");
            this.btnGo.Attributes.Add("onclick","check();");
            if(!this.IsPostBack)
            {                
                SetStyle();    
                SetEnable();
            }
        }

        Web Form Designer generated code#region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
            this.btnFirstPage.Click += new System.EventHandler(this.btnGo_Click);
            this.btnPrevPage.Click += new System.EventHandler(this.btnGo_Click);
            this.btnNextPage.Click += new System.EventHandler(this.btnGo_Click);
            this.btnLastPage.Click += new System.EventHandler(this.btnGo_Click);
            this.btnGo.Click += new System.EventHandler(this.btnGo_Click);
        }
        
        /**//// <summary>
        ///        Required method for Designer support - do not modify
        ///        the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {            
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        btnGo_Click#region btnGo_Click
        private void btnGo_Click(object sender, System.EventArgs e)
        {
            LinkButton linkbtn = sender as LinkButton;
            if( null == linkbtn )//button
            {
                Button btn = sender as Button;
                if( null == btn )
                {
                    return;
                }
                else
                {
                    int selPage = -1;
                    try
                    {
                        selPage =Int32.Parse(txtCurrentPage.Text);
                    }
                    catch
                    {
                        selPage = -1;
                    }
                    if (selPage > 0 && selPage <= PageCount)
                    {
                        ViewState["CurrentPageIndex"]  = selPage;
                    }
                    else
                    {
                        return;
                    }
                }
            }
            else//linkbutton
            {
                switch ( linkbtn.CommandArgument.Trim() )
                {
                    case "First":
                        ViewState["CurrentPageIndex"] = 1;
                        break;
                    case "Prev":
                        ViewState["CurrentPageIndex"] = (CurrentPageIndex > 1) ? CurrentPageIndex - 1 : 1;
                        break;
                    case "Next":
                        ViewState["CurrentPageIndex"] = (PageCount > CurrentPageIndex) ? CurrentPageIndex + 1 : PageCount;
                        break;
                    case "Last":                           
                        ViewState["CurrentPageIndex"]  = PageCount;
                        break;                
                    default:
                        break;
                }
            }
            SetEnable();//设置显示样式
            if (NavigationClick!=null)//调用事件 
            {
                NavigationClick( sender,e );
            }
        }
        #endregion

        SetStyle#region SetStyle
        private void SetStyle()
        {
            this.btnFirstPage.Attributes["style"] = "CURSOR: hand";
            this.btnLastPage.Attributes["style"] = "CURSOR: hand";
            this.btnNextPage.Attributes["style"] = "CURSOR: hand";
            this.btnPrevPage.Attributes["style"] = "CURSOR: hand";
        }
        #endregion

        SetEnable#region SetEnable
        // 应根据当前的CurrentPageIndex和pageCount设定哪些按钮可用        
        private void SetEnable()
        {
            this.lblTotal.Text =  PageCount.ToString();
            
            txtCurrentPage.Text =CurrentPageIndex.ToString();
            
            btnPrevPage.Enabled = false;
            btnNextPage.Enabled = false;
            
            if( PageCount >1 )
            {                    
                btnFirstPage.Enabled = btnPrevPage.Enabled = ( CurrentPageIndex >1 );
                btnNextPage.Enabled = btnLastPage.Enabled = ( CurrentPageIndex < PageCount );
            }
            else
            {                
                btnFirstPage.Enabled = false;
                btnLastPage.Enabled = false;
                btnPrevPage.Enabled = false;
                btnNextPage.Enabled = false;
            }
        }
        
        #endregion

        Property#region Property
        //获取或设置当前显示页的索引。                
        public int  CurrentPageIndex
        {
            get
            {
                object cpage=ViewState["CurrentPageIndex"];
                int pindex=(cpage==null)?1:(int)cpage;
                if(pindex>PageCount&&PageCount>0)
                    return PageCount;
                else if(pindex<1)
                    return 1;
                return pindex;
            }
            set
            {
                int cpage=value;
                if(cpage<1)
                    cpage=1;
                else if(cpage>this.PageCount)
                    cpage=this.PageCount;
                ViewState["CurrentPageIndex"]=cpage;
            }
        }

        // 获取或设置需要分页的所有记录的总数。    
        public int RecordCount
        {
            get
            {
                object obj=ViewState["Recordcount"];
                return (obj==null)?0:(int)obj;
            }
            set
            {
                ViewState["Recordcount"]=value;
                SetEnable();
            }
        }

        // 获取当前页之后的页的总数。        
        public int PagesRemain
        {
            get
            {
                return PageCount-CurrentPageIndex;
            }
        }
        // 获取或设置每页显示的项数。            
        public int PageSize
        {
            get
            {            
                object obj=ViewState["PageSize"];
                if (obj==null)
                {
                    obj= size;
                }                
                return (obj==null)?size:(int)obj;
            }
            set
            {
                int pageSize = value;
                
                if (Math.Abs(pageSize) == 0)
                    pageSize = size;

                ViewState["PageSize"]=pageSize;
            }
        }

        // 获取在当前页之后还未显示的剩余记录的项数。
        public int RecordsRemain
        {
            get
            {
                if(CurrentPageIndex<PageCount)
                {
                    return RecordCount-(CurrentPageIndex*PageSize);
                }
                else
                {
                    return 0;
                }
            }
        }

        // 获取所有要分页的记录需要的总页数。        
        public int PageCount
        {
            get{return (RecordCount > 0) ? (int)Math.Ceiling((double)RecordCount/(double)PageSize) : 1;}
        }

        public int XRecord
        {
            get
            {
                return int.Parse( System.Configuration.ConfigurationSettings.AppSettings["XRecord"].Trim() );
            }
        }
        #endregion Property
    }

2.建立DataGridPage.aspx
3.copy如下html代码

<HTML>
    <HEAD>
        <title>DataGridPage</title>
        <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
        <meta content="C#" name="CODE_LANGUAGE">
        <meta content="JavaScript" name="vs_defaultClientScript">
        <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
            <asp:datagrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 632px; POSITION: absolute; TOP: 40px"
                runat="server"></asp:datagrid><uc1:pager id="Pager1" runat="server"></uc1:pager><asp:datalist id="DataList1" style="Z-INDEX: 102; LEFT: 264px; POSITION: absolute; TOP: 40px"
                runat="server">
                <ItemTemplate>
                    <table>
                        <tr>
                            <td>用户ID:</td>
                            <td><%# DataBinder.Eval(Container.DataItem, "UserID") %></td>
                            <td>用户名:</td>
                            <td><%# DataBinder.Eval(Container.DataItem, "UserName") %></td>
                        </tr>
                    </table>
                </ItemTemplate>
            </asp:datalist>
            <asp:repeater id="Repeater1" runat="server">
                <HEADERTEMPLATE>
                    <table cellpadding="0" cellspacing="0" border="0">
                        <tr>
                            <td>用户ID</td>
                            <td>用户名:</td>
                        </tr>
                </HEADERTEMPLATE>
                <ITEMTEMPLATE>
                    <tr>
                        <td>
                            <%# DataBinder.Eval(Container.DataItem, "UserID")%>
                        </td>
                        <td><%# DataBinder.Eval(Container.DataItem, "UserName") %></td>
                    </tr>
                </ITEMTEMPLATE>
                <FOOTERTEMPLATE>
                    </table>
                </FOOTERTEMPLATE>
            </asp:repeater></form>
    </body>
</HTML>

4.拖入用户控件Pager.ascx
5.copy如下cs代码

public class DataGridPage : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.DataGrid DataGrid1;
        protected UserControl.Pager Pager1;//定义用户控件,根据用户控件所在目录做适当的调整
        protected System.Web.UI.WebControls.DataList DataList1;
        protected System.Web.UI.WebControls.Repeater Repeater1;
        public static string ConnectionString=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
        
        private void Page_Load(object sender, System.EventArgs e)
        {
            if (!this.IsPostBack)
            {                
                BindData();
            }
        }
        
        Bind Data#region Bind Data
        private void BindData()
        {            
            int output=0;
            this.SortExpression="UserID asc";
            this.FilterExpression="1=1";
            ds = GetList(this.Pager1.CurrentPageIndex,this.Pager1.PageSize,this.SortExpression,this.FilterExpression,ref output);

            if (ds!=null && ds.Tables.Count>0)
            {
                //DataGrid分页
                DataGrid1.DataSource = ds.Tables[0];
                DataGrid1.DataBind();
                //DataList分页
                DataList1.DataSource=ds.Tables[0];
                DataList1.DataBind();
                //Repeater分页
                Repeater1.DataSource=ds.Tables[0];
                Repeater1.DataBind();
            }
            Pager1.RecordCount=output;
        }
        #endregion        
    
        ExecSPDataSet#region ExecSPDataSet
        public static DataSet ExecSPDataSet(string sql,System.Data.IDataParameter[] paramers)
        {
            SqlConnection conn=new SqlConnection(ConnectionString);
            SqlCommand sqlcom=new SqlCommand(sql,conn);
            sqlcom.CommandType= CommandType.StoredProcedure ;

            foreach(System.Data.IDataParameter paramer in paramers)
            {
                sqlcom.Parameters.Add(paramer);
            }            
            conn.Open();
            
            SqlDataAdapter da=new SqlDataAdapter();
            da.SelectCommand=sqlcom;
            DataSet ds=new DataSet();
            da.Fill(ds);
        
            conn.Close();
            return ds;
        }

        #endregion

        GetList#region GetList
        public static DataSet GetList(int page_num,int row_in_page,string order_column,string comb_condition,ref int output)
        {            
            string sql="tp_Fetch_List";
            System.Data.SqlClient.SqlParameter[] p=new SqlParameter[5];
            
            p[0]=new SqlParameter();
            p[0].ParameterName ="@page_num";
            p[0].Value =page_num;
            p[0].DbType=System.Data.DbType.Int32;

            p[1]=new SqlParameter();
            p[1].ParameterName ="@row_in_page";
            p[1].Value =row_in_page;
            p[1].DbType=System.Data.DbType.Int32;

            p[2]=new SqlParameter();
            p[2].ParameterName ="@order_column";
            p[2].Value =order_column;
            p[2].DbType=System.Data.DbType.String;

            p[3]=new SqlParameter();
            p[3].ParameterName ="@row_total";
            p[3].Direction=System.Data.ParameterDirection.Output;
            p[3].DbType=System.Data.DbType.Int32;

            p[4]=new SqlParameter();
            p[4].ParameterName ="@comb_condition";
            p[4].Value =comb_condition;
            p[4].DbType=System.Data.DbType.String;
            DataSet ds=ExecSPDataSet(sql,p);
            if (p[3].Value!=DBNull.Value  && p[3].Value.ToString()!=string.Empty )
                output=Convert.ToInt32(p[3].Value);
            return ds;                
        }
        #endregion    

        property#region property
        private DataSet ds
        {
            get
            {
                return ViewState["ds"] as DataSet;
            }
            set
            {
                ViewState["ds"] = value;
            }
        }
        public string FilterExpression
        {
            get
            {
                if (this.ViewState["FilterExpression"]!=null)
                    return (string)this.ViewState["FilterExpression"];
                return string.Empty ;
            }
            set
            {
                this.ViewState["FilterExpression"]=value;

            }
        }

        public string SortExpression
        {
            get
            {
                if (this.ViewState["SortExpression"]!=null)
                    return (string)this.ViewState["SortExpression"];
                return string.Empty ;
            }
            set
            {
                this.ViewState["SortExpression"]=value;

            }
        }

        #endregion

        Web Form Designer generated code#region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
            this.Pager1.NavigationClick+=new EventHandler(Pager1_NavigationClick);
        }
        
        /**//// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {    
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        private void Pager1_NavigationClick(object sender, EventArgs e)
        {
            BindData();
        }
    }

6.测试表结构

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TestGrid]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TestGrid]
GO

CREATE TABLE [dbo].[TestGrid] (
    [UserID] [int] NOT NULL ,
    [UserName] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [Country] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [State] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [Enabled] [bit] NULL 
) ON [PRIMARY]
GO

7.测试存储过程

create PROCEDURE tp_Fetch_List(  
  @page_num                INT,
  @row_in_page             INT,
  @order_column            VARCHAR(50),
  @row_total               INT  OUTPUT,
  @comb_condition          VARCHAR(500)
)
AS
BEGIN
    SET NOCOUNT ON

    DECLARE 
      @jcc_status             INT,
      @sql                  NVARCHAR(4000),
      @row_ahead        INT
     
  SET @jcc_status = 0

  SET @row_ahead = (@page_num-1) * @row_in_page


SET @sql='SELECT TOP '+ cast(@row_in_page as varchar(255)) +  ' * FROM ( '
SET @sql = @sql + 'SELECT   *

FROM TestGrid 
 ) as A where 1=1'

IF LEN(@comb_condition)>0
        SET @sql = @sql + ' AND (' + @comb_condition  + ')'    

SET @sql = @sql + 'and UserID not in ( select UserID from ('
SET @sql = @sql + 'SELECT TOP ' + cast(@row_ahead as varchar(255)) + ' * From ('
SET @sql = @sql + 'SELECT   *

FROM TestGrid 
 ) as A where 1=1'
    IF LEN(@comb_condition)>0
        SET @sql = @sql + ' AND ( ' + @comb_condition  + ' )'    

    IF LEN(@order_column)>0
        BEGIN
            SET @sql = @sql + ' ORDER BY ' + @order_column    + ' ) AS B )'
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ) AS B )'
        END

    IF LEN(@order_column)>0
        BEGIN
            SET @sql = @sql + ' ORDER BY ' + @order_column     
        END

 print @sql

    EXEC (@sql)

    SET @sql= N'SELECT @row_total=COUNT(*) FROM ('
SET @sql = @sql + 'SELECT  *

FROM TestGrid 
 ) as A where 1=1'
IF LEN(@comb_condition)>0
        SET @sql = @sql + ' AND (' + @comb_condition  + ')'    

print @sql

    EXEC sp_executesql @sql,N'@row_total INT OUT',@row_total OUT

    IF @@ERROR != 0
    BEGIN
        SELECT @jcc_status = -98
    END


exit_bk:

-- exit with MS SQL Server error
  IF @jcc_status = -98
    BEGIN
      RAISERROR ('MS SQL Server error, please contact your system administrator.',16,1)WITH NOWAIT
      RETURN (@jcc_status)
    END

-- normal exit 
  RETURN (0)
END

GO

-- declare @aa int 
-- exec tp_Fetch_List 1,10,'',@aa out ,'1=1'
-- select @aa

8.源代码下载源代码下载

通用分页控件(DataGrid,DataList,Repeater都可以用它来分页)相关推荐

  1. asp.net下用AspNetPager分页控件对DataList进行分页

    第一次写博客,其实注册挺久的了,一直不知道写些什么好,原因是自己菜鸟一个,知识浅陋,不好出来献丑. 但是慢慢接触的多了,总觉得有些东西是不是该写一写,跟分享一下!不敢说对大家都有用,互相学习,也权当是 ...

  2. Winform分页控件之纯分页显示处理

    在之前介绍的Winform分页控件中,都以分页控件+显示表格控件作为一个整体性的控件,不可分开,这样做的目的是可以实现更多的操作,集成更多丰富的特性,减少我们开发的工作量,这种情况虽然适用于大多数的情 ...

  3. iOS:分页控件UIPageControl的使用

    分页控件:UIPageControl   功能:通常搭配滚动视图一起使用,设置pagingEnabled=YES即可,UIScrollView会被分割成多个独立页面,用户的滚动体验则变成了页面翻转,一 ...

  4. AspNetPager免费开源分页控件7.4.1版发布

    前几天发布的7.4版出现了postback分页情况下客户端脚本未注册的bug,非常抱歉,7.4.1版已修正这些问题,具体更新说明如下: 修正了Postback分页且显示页索引文本框的情况下,客户端脚本 ...

  5. Silverlight4.0(9) 之 分页控件轻量级的Session

    Silverlight中的DataPager分页控件实际上没什么好说的 PagedCollectionView pcv = new PagedCollectionView(list); pcv.Pag ...

  6. C# devexpress gridcontrol 分页 控件制作

    这个小小的功能实现起来还是有一点点复杂, 分页单独一个usercontrol 出来,导致查询换页 与gridcontrol页面分离,  一般通过换页事件通知girdcontrol 做出查询 查询来说有 ...

  7. antd表格分页控件显示英文page

    antd:[2021-1-26]解决表格分页控件英文显示的问题--使用之表格与分页控件的使用: 官网描述: Table组件pagination属性描述:object为Pagination组件api的属 ...

  8. angularjs实现的前端分页控件

    angularjs实现的前端分页控件 前言:之前写个一个jQuery的分页显示插件,http://blog.csdn.net/peakchen_90/article/details/52187175, ...

  9. Repeater使用 AspNetPager分页控件

    一.AspNetPager分页控件 分页是Web应用程序中最常用到的功能之一,在ASP.NET中,虽然自带了一个可以分页的DataGrid(asp.net 1.1)和GridView(asp.net ...

最新文章

  1. 如何避免jquery库和其它库的冲突
  2. 中兴高达和中兴啥关系_打通信息孤岛!中兴高达一体化通信指挥平台
  3. python中字典按键或键值排序
  4. python好学嘛-爬虫Python入门好学吗?学什么?
  5. Javascript的匿名函数与自执行
  6. 基于LZ77算法的文件压缩铺垫
  7. 模式对话框与非模式对话框的区别2
  8. python去除php、java、js、html、vue等类型注释字符方法实例
  9. Go实现Raft第三篇:命令和日志复制
  10. lcd驱动解析(二)
  11. Failed to create AppDomain 'xxx'. Exception has been Failed to create AppDomain
  12. 编写一个Java程序将当100,101,102,103,104,105个数以数组的形式写入到Dest.txt文件中,并以相反的顺序读出显示在屏幕上。
  13. 基于html5的城市公交查询系统,城市公交在线查询系统的设计与实现
  14. 添加最顶层js广告_js实现网站最上边可关闭的浮动广告条代码
  15. 雨滴win7计算机路径,win7雨滴桌面秀 Raindrop Desktop Show教程_计算机软件和应用程序_IT /计算机_信息...
  16. PD的CDM模型中的三种实体关系
  17. python字典合并 同key_Python 合并两个字典(Dictionary)中相同key的value的方法及示例代码...
  18. html td 水平居中,html元素水平居中的几种方法
  19. 笔记本屏幕亮度随着显示内容而变,时亮时暗
  20. 仿滴滴出行页面Demo

热门文章

  1. hge source explor 0x4 input module
  2. JAVA获取当前域名
  3. idear!2004-10-9
  4. uniapp前端循环数组取值方法
  5. 当Eclipse中maven识别不了本仓jar包是的解决方法
  6. php 开源模版大全
  7. ubuntu下文件夹锁的解锁方式
  8. Sonar LTS 版本 8.9发布|新特性
  9. Oracle11gR2 Centos6.x静默安装
  10. 淘宝天猫架构调整:原产业运营及发展中心负责人吹雪离职