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

PagedDataSource 分頁索引越界錯誤:原因分析與一行程式碼解決方案

     編輯:ASP.NET 基礎

錯誤現象

使用 PagedDataSource 實現分頁時,若在非第一頁(如第 3 頁)執行「重新查詢/換條件搜尋」,且新條件下的總頁數 小於 當前頁碼(例如新資料只有 2 頁),會拋出例外:

索引 2 不是非負數,就是大於行數 (ArgumentOutOfRangeException)

根本原因

  • CurrentPageIndex 保留舊值(如 2,代表第 3 頁)
  • 重新查詢後,PageCount 變為 2(索引上限為 1)
  • 設定 CurrentPageIndex = 2 時超出範圍,導致 DataBind() 失敗

解決方案:重新查詢前強制重設頁碼為 1

在執行新查詢/搜尋的按鈕事件中,先將頁碼重設為 1,再呼叫綁定方法:


protected void btnSearch_Click(object sender, EventArgs e)
{
    // 關鍵一行:重設為第一頁
    ViewState["CurrentPage"] = 0; // 或 lblCurrentPage.Text = "1";
    
    BindData(); // 內部會讀取 ViewState["CurrentPage"] 設定 CurrentPageIndex
}

完整防呆綁定寫法


private void BindData()
{
    int currentPage = (int)ViewState["CurrentPage"];
    
    // 取得資料並設定 PagedDataSource
    _pds.DataSource = GetData().DefaultView;
    _pds.AllowPaging = true;
    _pds.PageSize = 10;
    
    // 防呆:確保索引不超出範圍
    if (currentPage >= _pds.PageCount)
        currentPage = Math.Max(0, _pds.PageCount - 1);
    
    _pds.CurrentPageIndex = currentPage;
    ViewState["CurrentPage"] = currentPage; // 同步回寫修正後的值
    
    Repeater1.DataSource = _pds;
    Repeater1.DataBind();
}

最佳實踐總結

  1. 搜尋/重新查詢事件:必先重設 CurrentPage = 0(或 1-based 的 1)。
  2. BindData 方法:加入索引邊界檢查,自動修正超出範圍的頁碼。
  3. 頁碼儲存:使用 ViewState 而非控制項 Text 屬性,避免 ViewState 未啟用或被竄改。

遵循此原則,即可徹底杜絕分頁索引越界錯誤。

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