(轉)C#高效分頁代碼(不用存儲過程)


摘要:文章:C#高效分頁代碼(不用存儲過程) 摘要:首先創建一張表(要求ID自動編號):createtableredheadedfile(idintidentity(1,1,發表於北京聯高軟件有限公司技術文章欄目,代碼以高亮顯示。
關鍵字:過程, 存儲, 代碼, 高效, gt, system, web, int, viewstate, ui, id, currentpage, webcontrols, pages, this, linkbutton, using, gotopage, 數據


首先創建一張表(要求ID自動編號):

create table redheadedfile
(
   id int identity(1,1),
   filenames nvarchar(50),
   senduser nvarchar(50),
   primary key(id)
)

然后我們寫入50萬條記錄:

declare @i int
set @i=1
while @i<=500000
begin
    insert into redheadedfile(filenames,senduser) values("高效分頁算法測試數據" + str(i) ,"北京聯高軟件開發有限公司")
set @i=@i+1
end
GO

用Microsoft Visual Studio .NET 2005創建一張WebForm網頁。
前台代碼片段如下(webform8.aspx):
< %@ Page language="c#" Codebehind="WebForm8.aspx.cs" AutoEventWireup="false" Inherits="WebApplication6.WebForm8" %>
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
< HTML>
< HEAD>
< title>WebForm8</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:datalist id="datalist1" AlternatingItemStyle-BackColor="#f3f3f3" Width="100%" CellSpacing="0" CellPadding="0" Runat="server">
< ItemTemplate>
< table width="100%" border="0" cellspacing="0" cellpadding="0">
< tr>
< td width="30%" align="center"><%#DataBinder.Eval(Container.DataItem,"filenames")%></td>
< td width="30%" align="center"><%#DataBinder.Eval(Container.DataItem,"senduser")%></td>
< td width="30%" align="center"><%#DataBinder.Eval(Container.DataItem,"id")%></td>
< /tr>
< /table>
< /ItemTemplate>
< /asp:datalist>
< div align="center">共<asp:label id="LPageCount" Runat="server" ForeColor="#ff0000"></asp:label>頁/共
<asp:label id="LRecordCount" Runat="server" ForeColor="#ff0000"></asp:label>記錄
<asp:linkbutton id="Fistpage" Runat="server" CommandName="0">首頁</asp:linkbutton>   
< asp:linkbutton id="Prevpage" Runat="server" CommandName="prev">上一頁</asp:linkbutton>   
< asp:linkbutton id="Nextpage" Runat="server" CommandName="next">下一頁</asp:linkbutton>   
< asp:linkbutton id="Lastpage" Runat="server" CommandName="last">尾頁</asp:linkbutton>   
當前第<asp:label id="LCurrentPage" Runat="server" ForeColor="#ff0000"></asp:label>頁   
跳頁<asp:TextBox ID="gotoPage" Runat="server" Width="30px" MaxLength="5" AutoPostBack="True"></asp:TextBox>
< /div>
< /form>
< /body>
< /HTML>

后台代碼片段如下(webform8.aspx.cs)

  1. using System; 
  2. using System.Collections; 
  3. using System.ComponentModel; 
  4. using System.Data; 
  5. using System.Drawing; 
  6. using System.Web; 
  7. using System.Web.SessionState; 
  8. using System.Web.UI; 
  9. using System.Web.UI.WebControls; 
  10. using System.Web.UI.HtmlControls; 
  11. using System.Data.SqlClient; 
  12. using System.Configuration; 
  13. namespace WebApplication6 
  14.     /// <summary> 
  15.     /// WebForm8 的摘要說明。 
  16.     /// </summary> 
  17.     public class WebForm8 : System.Web.UI.Page 
  18.     { 
  19.         protected System.Web.UI.WebControls.LinkButton Fistpage; 
  20.         protected System.Web.UI.WebControls.LinkButton Prevpage; 
  21.         protected System.Web.UI.WebControls.LinkButton Nextpage; 
  22.         protected System.Web.UI.WebControls.LinkButton Lastpage; 
  23.         protected System.Web.UI.WebControls.DataList datalist1; 
  24.         protected System.Web.UI.WebControls.DropDownList mydroplist; 
  25.         protected System.Web.UI.WebControls.Label LPageCount; 
  26.         protected System.Web.UI.WebControls.Label LRecordCount; 
  27.         protected System.Web.UI.WebControls.Label LCurrentPage; 
  28.         protected System.Web.UI.WebControls.TextBox gotoPage; 
  29.         //定義每頁顯示記錄 
  30.         const int PageSize = 20; 
  31.         //定義幾個保存分頁參數變量 
  32.         int PageCount, RecCount, CurrentPage, Pages, JumpPage; 
  33.         private void Page_Load(object sender, System.EventArgs e) 
  34.         { 
  35.             if (!IsPostBack) 
  36.             { 
  37.                 //通過Calc()函數獲取總記錄數 
  38.                 RecCount = Calc(); 
  39.                 //計算總頁數(加上OverPage()函數防止有余數造成顯示數據不完整) 
  40.                 PageCount = RecCount / PageSize + OverPage(); 
  41.                 //保存總頁參數到ViewState(減去ModPage()函數防止SQL語句執行時溢出查詢范圍,可以用存儲過程分頁算法來理解這句) 
  42.                 ViewState["PageCounts"] = RecCount / PageSize - ModPage(); 
  43.                 //保存一個為0的頁面索引值到ViewState 
  44.                 ViewState["PageIndex"] = 0; 
  45.                 //保存PageCount到ViewState,跳頁時判斷用戶輸入數是否超出頁碼范圍 
  46.                 ViewState["JumpPages"] = PageCount; 
  47.                 //顯示LPageCount、LRecordCount的狀態 
  48.                 LPageCount.Text = PageCount.ToString(); 
  49.                 LRecordCount.Text = RecCount.ToString(); 
  50.                 //判斷跳頁文本框失效 
  51.                 if (RecCount <= 20) 
  52.                 { 
  53.                     gotoPage.Enabled = false
  54.                 } 
  55.                 //調用數據綁定函數TDataBind()進行數據綁定運算 
  56.                 TDataBind(); 
  57.             } 
  58.         } 
  59.         //計算余頁 
  60.         public int OverPage() 
  61.         { 
  62.             int pages = 0; 
  63.             if (RecCount % PageSize != 0) 
  64.                 pages = 1; 
  65.             else 
  66.                 pages = 0; 
  67.             return pages; 
  68.         } 
  69.         //計算余頁,防止SQL語句執行時溢出查詢范圍 
  70.         public int ModPage() 
  71.         { 
  72.             int pages = 0; 
  73.             if (RecCount % PageSize == 0 && RecCount != 0) 
  74.                 pages = 1; 
  75.             else 
  76.                 pages = 0; 
  77.             return pages; 
  78.         } 
  79.         // 計算總記錄的靜態函數 
  80.         // 本人在這里使用靜態函數的理由是:如果引用的是靜態數據或靜態函數, 
  81.         // 連接器會優化生成代碼,去掉動態重定位項(對海量數據表分頁效果更明顯)。 
  82.         // 希望大家給予意見、如有不正確的地方望指正。 
  83.         public static int Calc() 
  84.         { 
  85.             int RecordCount = 0; 
  86.             SqlCommand MyCmd = new SqlCommand("select count(*) as co from redheadedfile", MyCon()); 
  87.             SqlDataReader dr = MyCmd.ExecuteReader(); 
  88.             if (dr.Read()) 
  89.                 RecordCount = Int32.Parse(dr["co"].ToString()); 
  90.             MyCmd.Connection.Close(); 
  91.             return RecordCount; 
  92.         } 
  93.         //數據庫連接語句(從Web.Config中獲取) 
  94.         public static SqlConnection MyCon() 
  95.         { 
  96.             SqlConnection MyConnection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]); 
  97.             MyConnection.Open(); 
  98.             return MyConnection; 
  99.         } 
  100.         //對四個按鈕(首頁、上一頁、下一頁、尾頁)返回的CommandName值進行操作 
  101.         private void Page_OnClick(object sender, CommandEventArgs e) 
  102.         { 
  103.             //從ViewState中讀取頁碼值保存到CurrentPage變量中進行參數運算 
  104.             CurrentPage = (int)ViewState["PageIndex"]; 
  105.             //從ViewState中讀取總頁參數運算 
  106.             Pages = (int)ViewState["PageCounts"]; 
  107.             string cmd = e.CommandName; 
  108.             //篩選CommandName 
  109.             switch (cmd) 
  110.             { 
  111.                 case "next"
  112.                     CurrentPage++; 
  113.                     break
  114.                 case "prev"
  115.                     CurrentPage--; 
  116.                     break
  117.                 case "last"
  118.                     CurrentPage = Pages; 
  119.                     break
  120.                 default
  121.                     CurrentPage = 0; 
  122.                     break
  123.             } 
  124.             //將運算后的CurrentPage變量再次保存至ViewState 
  125.             ViewState["PageIndex"] = CurrentPage; 
  126.             //調用數據綁定函數TDataBind() 
  127.             TDataBind(); 
  128.         } 
  129.         private void TDataBind() 
  130.         { 
  131.             //從ViewState中讀取頁碼值保存到CurrentPage變量中進行按鈕失效運算 
  132.             CurrentPage = (int)ViewState["PageIndex"]; 
  133.             //從ViewState中讀取總頁參數進行按鈕失效運算 
  134.             Pages = (int)ViewState["PageCounts"]; 
  135.             //判斷四個按鈕(首頁、上一頁、下一頁、尾頁)狀態 
  136.             if (CurrentPage + 1 > 1) 
  137.             { 
  138.                 Fistpage.Enabled = true
  139.                 Prevpage.Enabled = true
  140.             } 
  141.             else 
  142.             { 
  143.                 Fistpage.Enabled = false
  144.                 Prevpage.Enabled = false
  145.             } 
  146.             if (CurrentPage == Pages) 
  147.             { 
  148.                 Nextpage.Enabled = false
  149.                 Lastpage.Enabled = false
  150.             } 
  151.             else 
  152.             { 
  153.                 Nextpage.Enabled = true
  154.                 Lastpage.Enabled = true
  155.             } 
  156.             //數據綁定到DataList控件 
  157.             DataSet ds = new DataSet(); 
  158.             //核心SQL語句,進行查詢運算(決定了分頁的效率:)) 
  159.             SqlDataAdapter MyAdapter = new SqlDataAdapter("Select Top " + PageSize + " * from redheadedfile where id not in(select top " + PageSize * CurrentPage + " id from redheadedfile order by id asc) order by id asc", MyCon()); 
  160.             MyAdapter.Fill(ds, "news"); 
  161.             datalist1.DataSource = ds.Tables["news"].DefaultView; 
  162.             datalist1.DataBind(); 
  163.             //顯示Label控件LCurrentPaget和文本框控件gotoPage狀態 
  164.             LCurrentPage.Text = (CurrentPage + 1).ToString(); 
  165.             gotoPage.Text = (CurrentPage + 1).ToString(); 
  166.             //釋放SqlDataAdapter 
  167.             MyAdapter.Dispose(); 
  168.         } 
  169.         #region Web 窗體設計器生成的代碼 
  170.         override protected void OnInit(EventArgs e) 
  171.         { 
  172.             // 
  173.             // CODEGEN: 該調用是 ASP.NET Web 窗體設計器所必需的。 
  174.             // 
  175.             InitializeComponent(); 
  176.             base.OnInit(e); 
  177.         } 
  178.         /// <summary> 
  179.         /// 設計器支持所需的方法 - 不要使用代碼編輯器修改 
  180.         /// 此方法的內容。 
  181.         /// </summary> 
  182.         private void InitializeComponent() 
  183.         { 
  184.             this.Fistpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick); 
  185.             this.Prevpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick); 
  186.             this.Nextpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick); 
  187.             this.Lastpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick); 
  188.             this.gotoPage.TextChanged += new System.EventHandler(this.gotoPage_TextChanged); 
  189.             this.Load += new System.EventHandler(this.Page_Load); 
  190.         } 
  191.         #endregion 
  192.         //跳頁代碼 
  193.         private void gotoPage_TextChanged(object sender, System.EventArgs e) 
  194.         { 
  195.             try 
  196.             { 
  197.                 //從ViewState中讀取可用頁數值保存到JumpPage變量中 
  198.                 JumpPage = (int)ViewState["JumpPages"]; 
  199.                 //判斷用戶輸入值是否超過可用頁數范圍值 
  200.                 if (Int32.Parse(gotoPage.Text) > JumpPage || Int32.Parse(gotoPage.Text) <= 0) 
  201.                 { 
  202.                     Response.Write("<script>alert("頁碼范圍越界!");location.href="WebForm8.aspx"</script>"); 
  203.                 } 
  204.                 else 
  205.                 { 
  206.                     //轉換用戶輸入值保存在int型InputPage變量中 
  207.                     int InputPage = Int32.Parse(gotoPage.Text.ToString()) - 1; 
  208.                     //寫入InputPage值到ViewState["PageIndex"]中 
  209.                     ViewState["PageIndex"] = InputPage; 
  210.                     //調用數據綁定函數TDataBind()再次進行數據綁定運算 
  211.                     TDataBind(); 
  212.                 } 
  213.             } 
  214.             //捕獲由用戶輸入不正確數據類型時造成的異常 
  215.             catch (Exception eXP) 
  216.             { 
  217.                 Response.Write("<script>alert("" + exp.Message + "");location.href="WebForm8.aspx"</script>"); 
  218.             } 
  219.         } 
  220.     } 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM