分页这个也是最多人问的,也是很基础很实用的。
网上有很多分页代码,要不是有前台就没后台,要不是有后台没前台,要不是就是控件,要不就是一大堆SQL代码,让人不知道怎样用。
力求最简单最易懂.三层架构那些就不搞了。
如果是access 就用这个SQLHELPER http://hi.csdn.net/link.php?url=http://blog.csdn.net/zzxap如果是MSSQL 就用这个sqlhelper http://www.cnblogs.com/zzxap/archive/2009/11/05/1596773.html
前台 如果你用的是 gridview 就把Repeater替换成gridview 。一样的。。
 <form id="frm01" action="" method="post" runat="server">
          <asp:ScriptManager ID="ScriptManager1" runat="server">
          </asp:ScriptManager>
          <asp:UpdatePanel ID="UpdatePanel1" runat="server">
          <ContentTemplate>
                   <div id="center-top" > <div class="fon">中间1</div> </div> 
                   <div id="center-content_Default2" > 
                  <asp:Repeater runat="server" Id="mainlist" >
                        <ItemTemplate>
                        <div id="pic-out" >
                            <li class="pic-a" >  Eval("product_type").ToString() </li>
                            <li class="pic-b" >Eval("product_desc").ToString() </li>
                        <li>价格<%#Eval("price")%> </li>
                        </div>
                        </ItemTemplate>
                    </asp:Repeater>
                 </div> 
              <div style="PADDING-TOP:10px; text-align:center"  >
&nbsp; 共<asp:label id="LPageCount" ForeColor="#ff0000" Runat="server"></asp:label>页
<asp:label id="LTotalCount" ForeColor="#ff0000" Runat="server"></asp:label>条记录
<asp:linkbutton id="Fistpage" Runat="server" CommandName="0" OnClick="Pager_Click">首頁</asp:linkbutton>
<asp:linkbutton id="Prevpage" Runat="server" CommandName="prev" OnClick="Pager_Click">上一頁</asp:linkbutton>
<asp:linkbutton id="Nextpage" Runat="server" CommandName="next" OnClick="Pager_Click">下一頁</asp:linkbutton>
<asp:linkbutton id="Lastpage" Runat="server" CommandName="last" OnClick="Pager_Click">尾頁</asp:linkbutton>当前第
<asp:label id="LCurrentPage" ForeColor="#ff0000" Runat="server"></asp:label>頁
           &nbsp; 转到第
           <asp:textbox id="gotoPage" Width="30px" Runat="server" AutoPostBack="True" MaxLength="5" ></asp:textbox>頁
           <asp:Label style=" POSITION: absolute" id="msgbox" runat="server" ForeColor="Red" BorderColor="Red"></asp:Label>
           </div>
           </ContentTemplate>
          </asp:UpdatePanel>
                 </form>

解决方案 »

  1.   

    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.OleDb;
    using System.Text;
    using Microsoft.ApplicationBlocks.Data;
    public partial class _Default : System.Web.UI.Page
    {
        string strpage = "";
        int PageCount = 0;
        int RecCount = 0;
        int CurrentPage = 0;
        int Current = 0;
        int Pages = 0; 
        int JumpPage = 0;//跳到第几页
        //每页显示记录数
        int PageSize =20; //每页显示20条记录
        string product_type = "";
        string type = "";
        string headid = "";
        private static int PageIndex=1;
        private static int PageCounts=1;
        private static int JumpPages=1;    protected void Page_Load(object sender, EventArgs e)
        {
            #region 接收从查询页面传递过来的参数。
            if (Request.QueryString["product_type"]!=null)
            {
                product_type = Server.UrlDecode(Request.QueryString["product_type"].ToString());
            }
            if (Request.QueryString["type"]!=null)
           {
               type = Server.UrlDecode(Request.QueryString["type"].ToString());       }
            #endregion        // headid = Request.QueryString["headid"];
            if (!IsPostBack)
            {
                //-------------------------------------------------------------
                    RecCount = Calc();
                    //计算总记录数
                    PageCount = RecCount / PageSize + OverPage();
                    //计算总页数
                    PageCounts = RecCount / PageSize - ModPage();
                    if (!string.IsNullOrEmpty(strpage))
                    {
                        //设置当前页为返回页
                         PageIndex= int.Parse(strpage);
                    }
                    else
                    {
                         PageIndex= 1;
                        //设置当前页为11
                        //Session["CurPage"] = 1;
                    }
                    JumpPages = PageCount;
                    LPageCount.Text = PageCount.ToString();
                    //总页数
                    LTotalCount.Text = RecCount.ToString();
                    //总记录数
                    if (RecCount <= PageSize)
                    {
                        gotoPage.Enabled = false;
                    }
                    else
                    {
                        gotoPage.Enabled = true;
                    }
                
                //-------------------------------------------------------------
              
                GetMainData(); //绑定数据
            }
        }
        #region "計算總行數"
    public int OverPage()
    {
        //算余
        int pages = 0;
        if (RecCount % PageSize != 0) {
            pages = 1;
        }
        else {
            pages = 0;
        }
        return pages;
    }
    public int ModPage()
    {
        //算余
        int pages = 0;
        if (RecCount % PageSize == 0 && RecCount != 0) 
        {
            pages = 1;
        }
        else {
            pages = 0;
        }
        return pages;
    }
    public int Calc()
    {
        //計算記錄總數
        DataSet ds= new DataSet();
        StringBuilder ass = new StringBuilder("Select count(id)  from M_product where 1=1 ");
        //如果有查询参数传入,就计算查询结果的总数
        if (type != null && type != "")
        {
            ass.Append("  and  [type]=" + type.Replace("'", "")  + " ");
        }
        if (product_type != null && product_type != "")
        {
            ass.Append("  and  product_type=" + product_type.Replace("'", "") + " ");
        }    string bss = ass.ToString();
        int RecordCount = 0;
        ds = SqlHelper.ExecuteDataset(SqlHelper.Conn, CommandType.Text, bss);    RecordCount = Int32.Parse(ds.Tables[0].Rows[0][0].ToString());
        //RecordCount = 10;
        if (RecordCount < PageSize) 
        {
            Fistpage.Enabled = false;
            Prevpage.Enabled = false;
            Nextpage.Enabled = false;
            Lastpage.Enabled = false;
        }
        else 
        {
            Fistpage.Enabled = true;
            Prevpage.Enabled = true;
            Nextpage.Enabled = true;
            Lastpage.Enabled = true;
        }
        return RecordCount;
    }
    #endregion
    #region "翻頁"
    public void Pager_Click(object sender, EventArgs e)
    {
        CurrentPage = (int)PageIndex;
        Pages = (int)PageCounts;
        string arg = ((LinkButton)sender).CommandName.ToString();
        switch (arg) {
            case "next":
                //下一页   如果要支持URL分页。 只要把CurrentPage 从URL获取就可以了
                if (CurrentPage < Pages + 1) 
                { CurrentPage = CurrentPage + 1; }
                break; 
               
            case "prev":
                //上一页
                if (CurrentPage != 1)
                {  CurrentPage -= 1; }
                break; 
               
            case "last":
                //最后一页
                CurrentPage = Pages + 1;
                break; 
                
            default:
                //首页
                CurrentPage = 1;
                break;           
        }
        //根据页数控制翻页按钮的可用与否
        if (CurrentPage > 1) {
            Fistpage.Enabled = true;
            Prevpage.Enabled = true;
        }
        else {
            Fistpage.Enabled = false;
            Prevpage.Enabled = false;
        }
        if (CurrentPage == Pages + 1) 
        {
            Nextpage.Enabled = false;
            Lastpage.Enabled = false;
        }
        else {
            Nextpage.Enabled = true;
            Lastpage.Enabled = true;
        }
         PageIndex= CurrentPage;
        //获取改變后的页码
       // //Session["CurPage"] = CurrentPage;
        //用户返回到当前页
           
        GetMainData();
    }
    //转到第几页
    protected void gotoPage_TextChanged(object sender, System.EventArgs e)
    {
        string asd = this.gotoPage.Text.Trim().ToString();
        JumpPage = (int)JumpPages;
        if (string.IsNullOrEmpty(asd)) {
            Alert("out of page range");
            return;
        }
        if (Int32.Parse(gotoPage.Text) > JumpPage || Int32.Parse(gotoPage.Text) <= 0 || string.IsNullOrEmpty(asd)) 
        {
            Alert("out of page range");//页数超出范围
            return;
        }
        else {
            int InputPage = Int32.Parse(gotoPage.Text.ToString());
             PageIndex= InputPage;
            ////Session["CurPage"] = InputPage;
            GetMainData();//绑定数据集
        }
    }
    #endregion   
        public void Alert(string rtt)
        {
            //顯示提示信息
           // System.Web.UI.ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "AjaxMsgBox", "alert('" + rtt + "');", true);
        }    private void GetMainData()
        {
            
            CurrentPage = (int)PageIndex;//获取当前页
            Pages = (int)PageCounts;//获取总页数
            LCurrentPage.Text = CurrentPage.ToString();
            int PageSize2 = PageSize * (CurrentPage - 1)+1;
            if (type != null && product_type!=null)//如果是手机
            {
                //用于函数参数的个数不对 在查询表达式 'isnull(max(xx.id),0)' 中。
               // SELECT 子句中包含一个保留字、拼写错误或丢失的参数,或标点符号不正确。
                //分页的核心语句,决定性能   row_number()也不错。也可以将以下语句改为存储过程。        
                StringBuilder sql = new StringBuilder("select  top  " + PageSize + "  * from M_product a ");                        sql.Append(" where   a.[id]>( select max(xx.[id])  from ( select  TOP " + PageSize2 + "  [id]  from M_product  where 1=1 ");
              
                if (type != null && type != "")
                {
                    sql.Append("  and  [type]=" + type.Replace("'", "")+"");
                }
                if (product_type != null && product_type != "")
                {
                    sql.Append("  and  product_type=" + product_type.Replace("'", "") + "");
                }            sql.Append("   ORDER BY [id] )xx   ) ");            if (type != null && type != "")
                {
                    sql.Append("  and  a.[type]=" + type.Replace("'", "") + "");
                }
                if (product_type != null && product_type != "")
                {
                    sql.Append("  and  a.product_type=" + product_type.Replace("'", "") + "");
                }            sql.Append("   ORDER BY a.[id] ");                mainlist.DataSource = SqlHelper.ExecuteDataset( SqlHelper.Conn, CommandType.Text,sql.ToString());
                    mainlist.DataBind();        }    }
    }
      

  2.   

    select top 页大小 * 
    from table1 
    where id> 
          (select max (id) from 
          (select top ((页码-1)*页大小) id from table1 order by id) as T) order by id 核心语句是这一条,其它都是枝叶
      

  3.   

    top max top 的效率是最高的一种。
    这里已经有人测试过了
    http://hi.baidu.com/ben19850410/blog/item/2167bbce55ea220592457ede.html
      

  4.   

    还以为是个通用的呢 原来也是一个.......
    select max (id) from ......如果我的主键是nvarchar 或 varchar 或 uniqueidentifier,你还能max么?
    .NET那么多优秀的框架 为何还要 "重复发明轮子"?
    只好丢个板砖了.......
      

  5.   

    我的分页思路是
    前台用
    <ul>
    //这部分用循环实现
    <li></li>
    <li></li>
    ...
    </ul>
    后台根据pageindex,pagesize去数据库读取一个dataTable
      

  6.   

    那如果是oracle呢,仅改sql语句吗
      

  7.   


    nvarchar 或 varchar 不能用max? ---能多谢拍砖,这本来就是没什么技术含量的。
      

  8.   

    如果是oracle 就改SQL语句 用rownumber 参数是一样的传
      

  9.   


    多表查询,只要 StringBuilder sql = new StringBuilder("select  top  " + PageSize + "  * from M_product a ");
    把这句改为  StringBuilder sql = new StringBuilder("select  top  " + PageSize + "  * from M_product a  left join 其它表 b  on a.id=b.ppid");在查询条件加上 and b.列名 =条件  即可又怎么不能扩充呢?这要看自己SQL的功底了。
      

  10.   

    有个疑问:
    别人说top效率比较低 楼主说最高
    翻页按钮是服务器控件?俺一直通过判断生成超链接 不知妥当不妥当 
    请教楼主
      

  11.   

    可以把left join 或innner join 后得到的结果表看成一个表。多表跟单表的原理是一样的
      

  12.   

    生成超链接也可以。
    你可以点击一个html的button 传一条URL到这个页面。
    然后这个页面的CurrentPage参数用request.querystring["xx"].Tostring() 来获取
      

  13.   

    我的SQL确是是不怎么地,但是应付分页查询,还是绰绰有余的。我刚才只是说的简单的多表连接查询,是简单的。如果复杂的呢,加上排序,加上条件,一条冗长的SQL语句,你能保证你在两年之后还能够看的明明白白吗?
      

  14.   

    绑定数据本来就要postback的。用服务器控件就可以了。
      

  15.   


    排序如果是多表 就order by 表1.name ,表2.xxx  
    如果多条件就appen条件进去。有什么复杂呢? if (xx != null )
                {
                    sql.Append("  and  表2.xx=" + product_type.Replace("'", "") + "");
                }
      

  16.   

    呵呵,之前还真没用过max(nvarchar||varchar)的,弥补了一点知识点,谢谢楼主指点啊。
      

  17.   

    如果我有两张表,表User1,User2,我两张表都需要分页,我需要在两个页面都写那么多的Append么?
    能重用?
      

  18.   

    LZ是没有理解我说的,也是怪我没有解释清楚。软件开发只是一个过程,一个软件系统的周期,更多的时间是在维护上。一个看不懂的代码何谈维护。好,就算你看的懂了,你保证你一辈子跟着这套代码走吗?你保证了只有你看的懂的代码,那么你怎么和你的战友一同协作开发。我记得以前有位CSDN前辈的一个签名好像是这样写的:“你能写得出机器看的懂的代码,可你也得写出人能看的懂的才行”。当你写的代码越来越复杂的时候,是很难保证让别人能够看懂的(当然,必须保证这个人不是个菜鸟)。
      

  19.   


    如果你嫌麻烦 ,就select * into #table1 from User1 a join User2 b on a.id=b.xxid 把两张表合并成一张表,放到临时表#table1中, 然后你就可以针对这个单表进行分页查询了
      

  20.   

    不错不错,支持风语者。
    sql server2005也可以用ROW_NUMBER分页.
    还有就是换页最好做个webcontrol
      

  21.   


    你可以看看微软的工程师写的petshop ,你觉得很好懂吗?水平有限,还要不断跟大家学习
      

  22.   


    如果你不想用临时表,请看66楼的回复 。直接在SQL里写left join 
    我觉得如果你真正看懂了那条SQL语句,就不会这样问了。
      

  23.   

    真正的逻辑 就是sql语句... 我觉得看sql语句不是很大问题的. 
    写不出很牛x的语句. 这种分页方式还是能看懂吧? 
    表不多可以连接, 太多 你可以做视图查询. 
      

  24.   

    User1 和 User2 没什么关系 没有可以连接的字段
    我要1000张表都需要分页 难道都要临时表?
      

  25.   

    忘了说using  Microsoft.ApplicationBlocks.Data;是sqlhelper 的命名空间来的。链接的SQLHELPER文件里有
      

  26.   

    其实,我不是说LZ的技术不好,方法不好,那不是我的原意。分页的查询方式,不才我也知道3 4种,可能还有更多,每种都可用,每种都是大家想了很久才想出来的自己的做法,这当然很好。只是在考虑代码功能和性能上,也应当尽量考虑日后对维护带来的麻烦。一旦这样写成习惯,改起来可不是见容易的事情。为什么asp.net那么棒,那么多现成的好的服务器控件都放在那里等着我们用,还要出asp.net MVC呢。不就是为了考虑日后的维护吗。