ASP.NET存儲過程自定義分頁詳解

  1. 原帖及討論:http://bbs.bccn.net/thread-207175-1-1.html
  2.     大家都知道asp.net中的Gridview。datalist等都可以自定義分頁,但是當你翻頁的時候,數據表中的所有數據都會加載到內存,重新綁定,當然要是數據量小的話,這是可以的,我們也很樂意用,原因簡單因爲方便,但是要是數據量是999999999999……,在信息爆炸的這個時代海量數據是經常的時,那麼這些控件自帶的分頁就顯得有些……
  3. 解決這個問題辦法就是自己動手……不多廢話了,看代碼:
  4. 1.首先我是用存儲過程來解決的,要弄懂這個問題,首先要從存儲過程下手,代碼如下:
  5. CREATE proc getdataset
  6. @TableList Varchar(200)='*',--搜索表的字段,比如:’id,datatime,job‘,用逗號隔開
  7. @TableName Varchar(30), --搜索的表名
  8. @SelectWhere Varchar(500)='',--搜索條件,這裏不用寫where,比如:job=’teacher‘and class='2'
  9. @SelectOrderId Varchar(20),--表主鍵字段名。比如:id
  10. @SelectOrder Varchar(200)='', --排序,可以使用多字段排序但主鍵字段必需在最前面.也可以不寫,比如:order by class asc
  11. @intPageNo int=1, --頁號
  12. @intPageSize int=10 ,--每頁顯示數
  13. @RecordCount int OUTPUT  --總記錄數(存儲過程輸出參數)
  14. as  
  15.     
  16. declare @TmpSelect      NVarchar(600)  
  17. declare @Tmp     NVarchar(600)  
  18. set nocount on--關閉計數
  19. set @TmpSelect = 'select @RecordCount = count(*) from '+@TableName+' '+@SelectWhere
  20. execute sp_executesql 
  21. @TmpSelect,    --執行上面的sql語句
  22. N'@RecordCount int OUTPUT' ,   --執行輸出數據的sql語句,output出總記錄數
  23. @RecordCount  OUTPUT
  24.   if (@RecordCount = 0)    --如果沒有貼子,則返回零
  25.        return 0
  26.        
  27.    /*判斷頁數是否正確*/
  28.   if (@intPageNo - 1) * @intPageSize > @RecordCount   --頁號大於總頁數,返回錯誤
  29.      return (-1)
  30. set nocount off--打開計數
  31. if @SelectWhere != '' 
  32. begin
  33. set @TmpSelect = 'select top '+str(@intPageSize)+' '+@TableList+' from '+@TableName+' where '+@SelectOrderId+' not in(select top '+str((@intPageNo-1)*@intPageSize)+' '+@SelectOrderId+' from '+@TableName+' '+@SelectWhere +' '+@SelectOrder+') and '+@SelectWhere +' '+@SelectOrder
  34. end
  35. else
  36. begin
  37. set @TmpSelect = 'select top '+str(@intPageSize)+' '+@TableList+' from '+@TableName+' where '+@SelectOrderId+' not in(select top '+str((@intPageNo-1)*@intPageSize)+' '+@SelectOrderId+' from '+@TableName+' '+@SelectOrder+') '+@SelectOrder
  38. end
  39. execute sp_executesql @TmpSelect
  40. return(@@rowcount)
  41. GO
  42. 其實代碼也很簡單,學編程的人基本上都是懂數據庫的,這個存儲過程估計不是問題。
  43. 其他的代碼我都做了解釋,有顏色的那段我沒有解釋,我在這裏解釋一下。其實也很簡單,大家來看:
  44. select top '+str((@intPageNo-1)*@intPageSize)+' '+@SelectOrderId+' from '+@TableName+' '+@SelectWhere +' '+@SelectOrder+'
  45. 這段代碼的執行結果是什麼了,是不是當前頁前面的主鍵的集合啊,現在我們從所有的表中選出主鍵的值不在這個結果的之內的pagesize個記錄不就是當前頁的內容了嗎?
  46. 2.aspx頁面就不用再將了吧?我這裏將代碼寫上:
  47. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="aa.aspx.cs" Inherits="_Default" %>
  48. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  49. <html xmlns="http://www.w3.org/1999/xhtml" >
  50. <head runat="server">
  51.     <title>無標題頁</title>
  52. </head>
  53. <body>
  54.     <form id="form1" runat="server">
  55.     <div>
  56.         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="180px" Width="867px">
  57.             <Columns>
  58.                 <asp:BoundField DataField="job_id" HeaderText="job_id" />
  59.                 <asp:BoundField DataField="job_desc" HeaderText="job_desc" />
  60.                 <asp:BoundField DataField="max_lvl" HeaderText="max_lxl" />
  61.             </Columns>
  62.         </asp:GridView>
  63.     
  64.     </div>
  65.            <asp:HyperLink ID="hylfirst" runat="server">首頁</asp:HyperLink>
  66.          
  67.         <asp:HyperLink ID="hylprev" runat="server">上一頁</asp:HyperLink>
  68.          
  69.         <asp:HyperLink ID="hylnext" runat="server">下一頁</asp:HyperLink>
  70.         <asp:HyperLink ID="hylend" runat="server">尾頁</asp:HyperLink>
  71.                第<asp:Label ID="lbRow" runat="server" Text="Label"></asp:Label>頁,
  72.           共<asp:Label ID="lbpage" runat="server" Text="Label"></asp:Label>頁,共<asp:Label
  73.             ID="lbRecord" runat="server" Text="Label"></asp:Label>條記錄,轉到<asp:TextBox ID="txtlink"
  74.                 runat="server" Width="29px"></asp:TextBox>
  75.         頁<asp:LinkButton ID="link" runat="server" OnClick="link_Click" TabIndex="1">轉到</asp:LinkButton>
  76.     </form>
  77. </body>
  78. </html> 
  79. 3.cs頁面其實也每頁什麼好講的,也就是一些常用的代碼罷了……我把代碼加上,大家看看,要是有疑問的可以回覆我再解釋:
  80. using System;
  81. using System.Data;
  82. using System.Configuration;
  83. using System.Collections;
  84. using System.Web;
  85. using System.Web.Security;
  86. using System.Web.UI;
  87. using System.Web.UI.WebControls;
  88. using System.Web.UI.WebControls.WebParts;
  89. using System.Web.UI.HtmlControls;
  90. using System.Data.SqlClient;
  91. public partial class _Default : System.Web.UI.Page
  92. {
  93.     protected void Page_Load(object sender, EventArgs e)
  94.     {
  95.         this.bind();
  96.         
  97.     }
  98.     protected void link_Click(object sender, EventArgs e)
  99.     {
  100.         int page = Convert.ToInt32(txtlink.Text);
  101.         Response.Redirect("aa.aspx?CurrentPage="+page+"");
  102.     }
  103.     public void bind()
  104.     {
  105.         int sumPage;
  106.         int pageNo = 1;
  107.         int pageSize = 3;
  108.         if (Request.QueryString["CurrentPage"] == null)
  109.         {
  110.             pageNo = 1;
  111.         }
  112.         else
  113.         {
  114.             pageNo = Int32.Parse(Request.QueryString["CurrentPage"]);
  115.         }
  116.         SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConStr"]);
  117.         SqlDataAdapter da = new SqlDataAdapter();
  118.         da.SelectCommand = new SqlCommand();
  119.         da.SelectCommand.Connection = conn;
  120.         da.SelectCommand.CommandText = "getdataset";
  121.         da.SelectCommand.CommandType = CommandType.StoredProcedure;
  122.         da.SelectCommand.Parameters.Add("@TableList", SqlDbType.VarChar, 200).Value = "job_id,job_desc,max_lvl";
  123.         da.SelectCommand.Parameters.Add("@TableName", SqlDbType.VarChar, 30).Value = "jobs";
  124.         //da.SelectCommand.Parameters.Add("@SelectWhere", SqlDbType.VarChar, 500).Value = "where d=1";
  125.         da.SelectCommand.Parameters.Add("@SelectOrderId", SqlDbType.VarChar, 20).Value = "job_id";
  126.         da.SelectCommand.Parameters.Add("@SelectOrder", SqlDbType.VarChar, 200).Value = "order by min_lvl asc";
  127.         da.SelectCommand.Parameters.Add("@intPageNo", SqlDbType.Int).Value = pageNo;
  128.         da.SelectCommand.Parameters.Add("@intPageSize", SqlDbType.Int).Value = pageSize;
  129.         da.SelectCommand.Parameters.Add("@RecordCount", SqlDbType.Int).Direction = ParameterDirection.Output;
  130.         da.SelectCommand.Parameters.Add("RowCount", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
  131.         DataSet ds = new DataSet();
  132.         da.Fill(ds, "jobs");
  133.         GridView1.DataSource = ds;
  134.         GridView1.DataBind();
  135.         Int32 RecordCount = (Int32)da.SelectCommand.Parameters["@RecordCount"].Value; //求出總記錄數,該值是output出來的值
  136.         Int32 RowCount = (Int32)da.SelectCommand.Parameters["RowCount"].Value;         //求出當前頁中的記錄數,在最後一頁不等於pagesize,
  137.         lbRecord.Text = RecordCount.ToString();
  138.         lbRow.Text = pageNo.ToString();
  139.         sumPage = (Int32)RecordCount / pageSize;
  140.         if (RecordCount % pageSize > 0)
  141.         {
  142.             sumPage = sumPage + 1;
  143.         }
  144.         lbpage.Text = sumPage.ToString();
  145.         if (pageNo > 1)
  146.         {
  147.             hylfirst.NavigateUrl = "aa.aspx?CurrentPage=1";
  148.             hylprev.NavigateUrl = string.Concat("aa.aspx?CurrentPage=""", pageNo - 1);
  149.         }
  150.         else
  151.         {
  152.             hylprev.NavigateUrl = "";
  153.             hylfirst.NavigateUrl = "";
  154.             hylfirst.Visible = false;
  155.             hylprev.Visible = false;
  156.         }
  157.         if (pageNo < sumPage)
  158.         {
  159.             hylend.NavigateUrl = string.Concat("aa.aspx?CurrentPage=""", sumPage);
  160.             hylnext.NavigateUrl = string.Concat("aa.aspx?CurrentPage=""", pageNo + 1);
  161.         }
  162.         else
  163.         {
  164.             hylnext.NavigateUrl = "";
  165.             hylend.NavigateUrl = "";
  166.             hylend.Visible = false;
  167.             hylnext.Visible = false;
  168.         }
  169.     }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章