首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

AspNetPager.dll 數據控件分頁完整接入指南

     編輯:ASP.NET 基礎

快速開始四步走

步驟 1:下載並引用

  • 官網下載 `AspNetPager.dll`
  • 專案右鍵「添加引用」→ 瀏覽選中 dll,或直接放入 `Bin` 目錄

步驟 2:工具箱添加控件

  1. 工具箱空白處右鍵 →「選擇項目」
  2. 「瀏覽」選中 `AspNetPager.dll` → 確定
  3. 工具箱出現 `AspNetPager` 控件(圖標為藍色分頁圖示)

步驟 3:頁面拖拽與屬性配置


<webdiyer:AspNetPager ID="AspNetPager1" runat="server" 
    PageSize="10" 
    HorizontalAlign="Center" 
    FirstPageText="首頁" LastPageText="尾頁" 
    NextPageText="下一頁" PrevPageText="上一頁"
    ShowPageIndexBox="Always" 
    OnPageChanged="AspNetPager1_PageChanged">
</webdiyer:AspNetPager>

步驟 4:後台綁定邏輯(以 Repeater 為例)


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"`

進階技巧

1. 自定義顯示信息


CustomInfoHTML="共<font color='red'>%PageCount%</font>頁,第<font color='red'>%CurrentPageIndex%</font>頁"
ShowCustomInfoSection="Left"

2. 輸入框跳轉


PageIndexBoxType="TextBox"
ShowPageIndexBox="Always"
TextBeforeInputBox="轉到第"
TextAfterInputBox="頁"

3. 效能優化:緩存總記錄數


if (Cache["TotalCount"] == null)
{
    Cache["TotalCount"] = GetTotalCount(); // 耗時查詢
    Cache.Insert("TotalCount", count, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration);
}
AspNetPager1.RecordCount = (int)Cache["TotalCount"];

常見坑點

  • ❌ 忘記賦值 `RecordCount` → 分頁條不顯示或異常
  • ❌ `CurrentPageIndex` 當作 0-based 用 → 首頁顯示第 2 頁數據
  • ❌ `PageChanged` 事件中未重新查詢數據源 → 翻頁數據不變
  • ❌ `PagedDataSource.CurrentPageIndex` 未減 1 → 索引越界

適用於所有數據控件

GridView、DataList、ListView、Repeater、DetailsView 等均可通過 `PagedDataSource` 中介實現分頁,邏輯完全一致。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved