ASP.NET 三大列表控制項中,唯 GridView 內建分頁。若追求樣式彈性常用 DataList/Repeater,需自行實作分頁。本文對比三種手動分頁模式。
<asp:GridView ID="gvShow" AllowPaging="True" PageSize="2"
OnPageIndexChanging="gvShow_PageIndexChanging" runat="server" />
<asp:DropDownList ID="DropDownList1" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" runat="server" />
protected void Page_Load(...) {
if (!IsPostBack) { Bind(); FillPageNumbers(); }
}
private void FillPageNumbers() {
DropDownList1.Items.Clear();
for (int i=1; i<=gvShow.PageCount; i++) DropDownList1.Items.Add(i.ToString());
}
protected void DropDownList1_SelectedIndexChanged(...) {
gvShow.PageIndex = Convert.ToInt32(DropDownList1.SelectedValue)-1;
Bind();
}
protected void gvShow_PageIndexChanging(...) {
gvShow.PageIndex = e.NewPageIndex; Bind();
}
PagedDataSource 包裝 DataView,設定 AllowPaging、PageSize、CurrentPageIndex,再繫結至列表控制項,配合自訂分頁導航 UI(首頁、上頁、下頁、尾頁、頁碼)。