以下介紹兩種分頁,用AspNetPager和ViewState
一.AspNetPager的用法
1. 複製AspNetPager.dll到bin目錄,在工具箱->選擇項->瀏覽,添加bin下的引用。
2. 從工具箱拖個AspNetPager,改如下屬性:
PageSize--每頁顯示的記錄數
CustomInfoHTML--自訂顯示文本,一般為“第%CurrentPageIndex%頁 共%PageCount%頁”
ShowCustomInfoSection--顯示當前頁和總頁數資訊,值為Never,Right,Left
AlwaysShow--總是顯示分頁控制項
PageIndexBoxType--指定頁索引框的顯示類型,值為文字框,下拉式清單方塊
ShowPageIndexBox--指定頁索引框的顯示方式,值為Always,Never,Auto
TextAfterPageIndexBox--頁索引框後的常值內容,一般為“頁”
TextBeforePageIndexBox--頁索引框前的常值內容,一般為“轉到”
顯示如下
3. 在AspNetPager的PageChanged事件中寫如下代碼:
protected void AspNetPager1_PageChanged(object sender, EventArgs e)
{
Databind();
}
private void Databind()
{
PagedDataSource pds = new PagedDataSource();
pds.DataSource = List<T>;
pds.AllowPaging = true;
pds.PageSize = AspNetPager1.PageSize; //AspNetPager1是ID
AspNetPager1.RecordCount = pds.DataSourceCount;
pds.CurrentPageIndex = AspNetPager1.CurrentPageIndex - 1;
GridView1.DataSource = pds; //綁定到GridView
GridView1.DataBind();
}
二. ViewState
1.四個按鈕觸發以下同一個Click事件:
protected void Button1_Click(object sender, EventArgs e)
{
PagedDataSource pds = new PagedDataSource();
pds .DataSource = ds.Tables[0].DefaultView;
pds .AllowPaging = true;
pds .PageSize = 10;
Button lb = (Button)sender;
int page = 0;
switch (lb.Text)
{
case "首頁":
ViewState["vs"] = 0;
break;
case "下一頁":
if (ViewState["vs"] != null)
{
page = Convert.ToInt16(ViewState["vs"]);
}
if (page < pds.PageCount - 1)
page++;
ViewState["vs"] = page;
break;
case "上一頁":
if (ViewState["vs"] != null)
{
page = Convert.ToInt16(ViewState["vs"]);
}
if (page > 0)
page--;
ViewState["vs"] = page;
break;
case "尾頁":
ViewState["vs"] = pds.PageCount - 1;
break;
}
databind();
}
private void databind()
{
int page = 0;
if (ViewState["vs"] != null)
{
page = Convert.ToInt16(ViewState["vs"]);
}
Status = "<font color=green>當前第" + (page + 1) + "/" + pds.PageCount + "頁</font>";
pds.CurrentPageIndex = page;
Repeater1.DataSource = pds;
Repeater1.DataBind();
}