<asp:GridView ID="gvwDesignationName" runat="server"
AllowPaging="true"
PageSize="10"
OnPageIndexChanging="gvwDesignationName_PageIndexChanging">
</asp:GridView>
private void BindData()
{
// 從數據庫獲取 DataTable/DataSet
gvwDesignationName.DataSource = GetData();
gvwDesignationName.DataBind();
}
protected void gvwDesignationName_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwDesignationName.PageIndex = e.NewPageIndex;
BindData();
}
使用 <PagerTemplate> 完全控制分頁 UI:頁碼顯示、首頁/尾頁、上一頁/下一頁、跳轉輸入框。
<PagerTemplate>
當前第:
<asp:Label ID="LabelCurrentPage" runat="server" Text='<%# ((GridView)Container.NamingContainer).PageIndex + 1 %>' />
頁/共:
<asp:Label ID="LabelPageCount" runat="server" Text='<%# ((GridView)Container.NamingContainer).PageCount %>' />
頁
<asp:LinkButton ID="LinkButtonFirstPage" runat="server" CommandArgument="First" CommandName="Page"
Visible='<%# ((GridView)Container.NamingContainer).PageIndex != 0 %>'>首頁</asp:LinkButton>
<asp:LinkButton ID="LinkButtonPreviousPage" runat="server" CommandArgument="Prev" CommandName="Page"
Visible='<%# ((GridView)Container.NamingContainer).PageIndex != 0 %>'>上一頁</asp:LinkButton>
<asp:LinkButton ID="LinkButtonNextPage" runat="server" CommandArgument="Next" CommandName="Page"
Visible='<%# ((GridView)Container.NamingContainer).PageIndex != ((GridView)Container.NamingContainer).PageCount - 1 %>'>下一頁</asp:LinkButton>
<asp:LinkButton ID="LinkButtonLastPage" runat="server" CommandArgument="Last" CommandName="Page"
Visible='<%# ((GridView)Container.NamingContainer).PageIndex != ((GridView)Container.NamingContainer).PageCount - 1 %>'>尾頁</asp:LinkButton>
轉到第
<asp:TextBox ID="txtNewPageIndex" runat="server" Width="20px" Text='<%# ((GridView)Container.Parent.Parent).PageIndex + 1 %>' />
頁
<asp:LinkButton ID="btnGo" runat="server" CausesValidation="False" CommandArgument="-2" CommandName="Page" Text="GO" />
</PagerTemplate>
protected void gvwDesignationName_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView theGrid = sender as GridView;
int newPageIndex = 0;
if (e.NewPageIndex == -3) // GO 按鈕 CommandArgument="-2" 經處理後為 -3?
{
// 獲取分頁行中的 TextBox
GridViewRow pagerRow = theGrid.BottomPagerRow;
TextBox txtNewPageIndex = pagerRow?.FindControl("txtNewPageIndex") as TextBox;
if (txtNewPageIndex != null && int.TryParse(txtNewPageIndex.Text, out int idx))
newPageIndex = idx - 1;
}
else
{
newPageIndex = e.NewPageIndex;
}
// 邊界保護
newPageIndex = Math.Max(0, Math.Min(newPageIndex, theGrid.PageCount - 1));
theGrid.PageIndex = newPageIndex;
BindData();
}
Container.NamingContainer 獲取當前 GridView 實例。CommandName="Page" 告訴 GridView 觸發分頁事件,CommandArgument 傳遞目標頁標識。BottomPagerRow / TopPagerRow 訪問分頁模板中的控件。BindData())使分頁生效。新項目優先使用 GridView 替代品:ListView + DataPager(更靈活)、前端分頁組件(如 DataTables.js、Bootstrap Pagination)配合 WebAPI 返回 JSON,實現真正的前後端分離。