<webdiyer:AspNetPager ID="AspNetPager1" runat="server"
PageSize="10"
HorizontalAlign="Center"
FirstPageText="首頁" LastPageText="尾頁"
NextPageText="下一頁" PrevPageText="上一頁"
ShowPageIndexBox="Always"
OnPageChanged="AspNetPager1_PageChanged">
</webdiyer:AspNetPager>
private void DatasBind()
{
// 1. 設置總記錄數(關鍵!)
this.AspNetPager1.RecordCount = ds.Tables[0].Rows.Count;
// 2. 配置 PagedDataSource
PagedDataSource pds = new PagedDataSource();
pds.AllowPaging = true;
pds.PageSize = AspNetPager1.PageSize;
pds.CurrentPageIndex = AspNetPager1.CurrentPageIndex - 1; // PagedDataSource 從 0 開始
pds.DataSource = ds.Tables[0].DefaultView;
// 3. 綁定 Repeater
rpttandy.DataSource = pds;
rpttandy.DataBind();
}
protected void AspNetPager1_PageChanged(object sender, EventArgs e)
{
DatasBind(); // 換頁時重新綁定
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// 首次加載數據源 ds
GetData();
DatasBind();
}
}
| 屬性 | 說明 | 常用值 |
|---|---|---|
| RecordCount | 總記錄數,**必須賦值** | `dt.Rows.Count` |
| PageSize | 每頁條數 | 10, 20, 50 |
| CurrentPageIndex | 當前頁碼(1-based) | 只讀,配合 `e.NewPageIndex` |
| NumericButtonCount | 數字按鈕顯示個數 | 10 |
| PageChanged | 換頁後事件 | 重新綁定入口 |
| PageChanging | 換頁前事件(可取消) | `e.Cancel = true` |
| UrlPaging | 啟用 URL 分頁 | `true` + `UrlPageIndexName="page"` |
CustomInfoHTML="共<font color='red'>%PageCount%</font>頁,第<font color='red'>%CurrentPageIndex%</font>頁"
ShowCustomInfoSection="Left"
PageIndexBoxType="TextBox"
ShowPageIndexBox="Always"
TextBeforeInputBox="轉到第"
TextAfterInputBox="頁"
if (Cache["TotalCount"] == null)
{
Cache["TotalCount"] = GetTotalCount(); // 耗時查詢
Cache.Insert("TotalCount", count, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration);
}
AspNetPager1.RecordCount = (int)Cache["TotalCount"];
GridView、DataList、ListView、Repeater、DetailsView 等均可通過 `PagedDataSource` 中介實現分頁,邏輯完全一致。