使用 PagedDataSource 實現分頁時,若在非第一頁(如第 3 頁)執行「重新查詢/換條件搜尋」,且新條件下的總頁數 小於 當前頁碼(例如新資料只有 2 頁),會拋出例外:
索引 2 不是非負數,就是大於行數 (ArgumentOutOfRangeException)
CurrentPageIndex 保留舊值(如 2,代表第 3 頁)PageCount 變為 2(索引上限為 1)CurrentPageIndex = 2 時超出範圍,導致 DataBind() 失敗在執行新查詢/搜尋的按鈕事件中,先將頁碼重設為 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();
}
CurrentPage = 0(或 1-based 的 1)。ViewState 而非控制項 Text 屬性,避免 ViewState 未啟用或被竄改。遵循此原則,即可徹底杜絕分頁索引越界錯誤。