在頁面檔案的DataList中加入以下四個按鈕
<asp:linkbutton id='FirstLB' runat='server' OnCommand='LinkButton_Click' CommandName='f'>第一頁</asp:linkbutton>
<asp:linkbutton id='PreviousLB' runat='server' OnCommand='LinkButton_Click' CommandName='p'>上一頁</asp:linkbutton>
<asp:linkbutton id='NextLB' runat='server' OnCommand=LinkButton_Click CommandName='n'>下一頁</asp:linkbutton>
<asp:linkbutton id='EndLB' runat='server' OnCommand=LinkButton_Click CommandName='e'>最後一頁</asp:linkbutton>
背景代碼:
先聲明幾個公共變量 int CurrentPage;//目前頁數
int PageSize; //每頁條數
int PageCount; //總頁數
int RecordCount;//總條數
int[] j=null;
頁面加載的時候 string productIds = Request.Params["分頁的依據"];
string[] productId = productIds.Split(',');
j = new int[productId.Length];
for (int m = 0; m < productId.Length; m++)
{
j= Convert.ToInt32(productId); } PageSize = 10;//每頁10條記錄
if (!Page.IsPostBack)
{
CurrentPage = 0;//目前頁習慣設為0
ViewState["PageIndex"] = 0;//頁索引也設為0
//計算總共有多少記錄
RecordCount = DAL.Counts(j);
//計算總共有多少頁
if (RecordCount % PageSize == 0)
{
PageCount = RecordCount / PageSize;
}
else
{
PageCount = RecordCount / PageSize + 1;
}
this.TotalLbl.Text = PageCount.ToString();//顯示總頁數
ViewState["PageCount"] = PageCount;//會話session 對整個 application 有效 ,而視圖狀态 viewstate相當于某個頁面的 session
this.DataListBind(j);//不可以放在初始化條件之前就綁定,那樣的話,如果僅有一頁的資料,“下一頁”頁仍然顯示
} private void DataListBind(int[] j)
{
try
{
int StartIndex = CurrentPage * PageSize;//設定導入的起終位址
DataSet ds = DAL.SearchByID(j,StartIndex,PageSize,"内容");
this.ListProduct.DataSource = ds.Tables[0].DefaultView;
this.ListProduct.DataBind();
this.PreviousLB.Enabled = true;
this.NextLB.Enabled = true;
if (CurrentPage == (PageCount - 1)) this.NextLB.Enabled = false;//當為最後一頁時,下一頁連結按鈕不可用
if (CurrentPage == 0) this.PreviousLB.Enabled = false;//當為第一頁時,上一頁按鈕不可用
this.CurrentLbl.Text = (CurrentPage + 1).ToString();//目前頁數
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public void LinkButton_Click(Object sender, CommandEventArgs e)//自己編寫的按鈕點選事件
{
CurrentPage = (int)ViewState["PageIndex"];//獲得目前頁索引
PageCount = (int)ViewState["PageCount"];//獲得總頁數
string cmd = e.CommandName;
//判斷cmd,以判定翻頁方向
switch (cmd)
{
case "p"://上一頁
if (CurrentPage > 0) CurrentPage--;
break;
case "n":
if (CurrentPage < (PageCount - 1)) CurrentPage++;//下一頁
break;
case "f"://第一頁
CurrentPage = 0;
break;
case "e"://最後一頁
CurrentPage = PageCount - 1;
break;
case "j"://跳轉到第幾頁
if (this.TextBox1.Text.Trim() == null || Int32.Parse(this.TextBox1.Text.Trim()) > PageCount)//如果輸入數字為空或超出範圍則傳回
{
return;
}
else
{
CurrentPage = Int32.Parse(this.TextBox1.Text.ToString()) - 1;
break;
}
}
ViewState["PageIndex"] = CurrentPage;//獲得目前頁
this.DataListBind(j);//重新将DataList綁定到資料庫
}
}