首先創建一張表(要求ID自動編號):
create table redheadedfile(
id int identity(1,1),
filenames nvarchar(20),
senduser nvarchar(20),
primary key(id)
)
然後我們寫入50萬條記錄:
declare @i int
set @i=1
while @i<=500000
begin
insert into redheadedfile(filenames,senduser) values('我的分頁算法','陸俊銘')
set @i=@i+1
end
GO
用Microsoft Visual Studio .Net 2003創建一張WebForm網頁(本人起名webform8.ASPx)
前台代碼片段如下(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> &
;nbsp; 當前第<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)
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClIEnt;
using System.Configuration;
namespace WebApplication6
{
/// <summary>
/// WebForm8 的摘要說明。
/// </summary>
public class WebForm8 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.LinkButton Fistpage;
protected System.Web.UI.WebControls.LinkButton Prevpage;
protected System.Web.UI.WebControls.LinkButton Nextpage;
protected System.Web.UI.WebControls.LinkButton Lastpage;
protected System.Web.UI.WebControls.DataList datalist1;
protected System.Web.UI.WebControls.DropDownList mydroplist;
protected System.Web.UI.WebControls.Label LPageCount;
protected System.Web.UI.WebControls.Label LRecordCount;
protected System.Web.UI.WebControls.Label LCurrentPage;
protected System.Web.UI.WebControls.TextBox gotoPage;
const int PageSize=20;//定義每頁顯示記錄
int PageCount,RecCount,CurrentPage,Pages,JumpPage;//定義幾個保存分頁參數變量
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
RecCount = Calc();//通過Calc()函數獲取總記錄數
PageCount = RecCount/PageSize + OvERPage();//計算總頁數(加上OverPage()函數防止有余數造成顯示
數據不完整)
VIEwState["PageCounts"] = RecCount/PageSize -
ModPage();//保存總頁參數到VIEwState(減去ModPage()函數防止SQL語句執行時溢出查詢范圍,可以用存儲過程分頁算法來理解這句)
ViewState["PageIndex"] = 0;//保存一個為0的頁面索引值到VIEwState
ViewState["JumpPages"] = PageCount;//保存PageCount到VIEwState,跳頁時判斷用戶輸入數是否超出頁
碼范圍
//顯示LPageCount、LRecordCount的狀態
LPageCount.Text = PageCount.ToString();
LRecordCount.Text = RecCount.ToString();
//判斷跳頁文本框失效
if(RecCount <= 20)
gotoPage.Enabled = false;
TDataBind();//調用數據綁定函數TDataBind()進行數據綁定運算
}
}
//計算余頁
public int OverPage()
{
int pages = 0;
if(RecCount%PageSize != 0)
pages = 1;
else
&n
bsp; pages = 0;
return pages;
}
//計算余頁,防止SQL語句執行時溢出查詢范圍
public int ModPage()
{
int pages = 0;
if(RecCount%PageSize == 0 && RecCount != 0)
pages = 1;
else
pages = 0;
return pages;
}
/*
*計算總記錄的靜態函數
*本人在這裡使用靜態函數的理由是:如果引用的是靜態數據或靜態函數,連接器會優化生成代碼,去掉動態重定位項(對
海量數據表分頁效果更明顯)。
*希望大家給予意見、如有不正確的地方望指正。
*/
public static int Calc()
{
int RecordCount = 0;
SqlCommand MyCmd = new SqlCommand("select count(*) as co from redheadedfile",MyCon());
SqlDataReader dr = MyCmd.ExecuteReader();
if(dr.Read())
RecordCount = Int32.Parse(dr["co"].ToString());
MyCmd.Connection.Close();
return RecordCount;
}
//數據庫連接語句(從Web.Config中獲取)
public static SqlConnection MyCon()
{
SqlConnection MyConnection = new SqlConnection(ConfigurationSettings.APPSettings["DSN"]);
MyConnection.Open();
return MyConnection;
}
//對四個按鈕(首頁、上一頁、下一頁、尾頁)返回的CommandName值進行操作
private void Page_OnClick(object sender, CommandEventArgs e)
{
CurrentPage = (int)ViewState["PageIndex"];//從VIEwState中讀取頁碼值保存到CurrentPage變量中進行參數運
算
Pages = (int)ViewState["PageCounts"];//從VIEwState中讀取總頁參數運算
string cmd = e.CommandName;
switch(cmd)//篩選CommandName
{
case "next":
CurrentPage++;
break;
case "prev":
CurrentPage--;
break;
case "last":
CurrentPage = Pages;
break;
default:
CurrentPage = 0;
break;
}
ViewState["PageIndex"] = CurrentPage;//將運算後的CurrentPage變量再次保存至VIEwState
TDataBind();//調用數據綁定函數TDataBind()
}
private void TDataBind()
{
CurrentPage = (int)ViewState["PageIndex"];//從VIEwState中讀取頁碼值保存到CurrentPage變量中進行按鈕失
效運算
Pages = (int)ViewState["PageCounts"];//從VIEwState中讀取總頁參數進行按鈕失效運算
//判斷四個按鈕(首頁、上一頁、下一頁、尾頁)狀態
if (CurrentPage + 1 > 1)
{
Fistpage.Enabled = true;
Prevpage.Enabled = true;
}
&nb
sp; else
{
Fistpage.Enabled = false;
Prevpage.Enabled = false;
}
if (CurrentPage == Pages)
{
Nextpage.Enabled = false;
Lastpage.Enabled = false;
}
else
{
Nextpage.Enabled = true;
Lastpage.Enabled = true;
}
//數據綁定到DataList控件
DataSet ds = new DataSet();
//核心SQL語句,進行查詢運算(決定了分頁的效率:))
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());
MyAdapter.Fill(ds,"news");
datalist1.DataSource = ds.Tables["news"].DefaultVIEw;
datalist1.DataBind();
//顯示Label控件LCurrentPaget和文本框控件gotoPage狀態
LCurrentPage.Text = (CurrentPage+1).ToString();
gotoPage.Text = (CurrentPage+1).ToString();
//釋放SqlDataAdapter
MyAdapter.Dispose();
}
#region Web 窗體設計器生成的代碼
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 該調用是 ASP.Net Web 窗體設計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 設計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.Fistpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
this.Prevpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
this.Nextpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
this.Lastpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
this.gotoPage.TextChanged += new System.EventHandler(this.gotoPage_TextChanged);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
//跳頁代碼
private void gotoPage_TextChanged(object sender, System.EventArgs e)
{
try
{
JumpPage = (int)ViewState["JumpPages"];//從VIEwState中讀取可用頁數值保存到JumpPage變量中
//判斷用戶輸入值是否超過可用頁數范圍值
if(Int32.Parse(gotoPage.Text) > JumpPage || Int32.Parse(gotoPage.Text) <= 0)
Response.Write("<script>alert('頁碼范圍越界!');location.href='WebForm8.ASPx'</script>"); else
{
int InputPage = Int32.Parse(gotoPage.Text.ToString()) - 1;//轉換用戶輸入值保存在int型
InputPage變量中
ViewState["PageIndex"] = InputPage;//寫入InputPage值到VIEwState["PageIndex"]中
TDataBind();//調用數據綁定函數TDataBind()再次進行數據綁定運算
}
}
//捕獲由用戶輸入不正確數據類型時造成的異常
catch(Exception exp)
{
Response.Write("<script>alert('"+exp.Message+"');location.href='WebForm8.ASPx'</script>");
}
}
}
}