首先創建一張表(要求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 @[email protected]+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> 當前第<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
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;
}
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>");
}
}
}
}
大家來試試,效率是不是高了很多?
如有不妥望大家來指正
新聞熱點
疑難解答
圖片精選