DataPager 是 ASP.NET 內建的強大分頁控制項,無需撰寫預存程序即可為 ListView、GridView 等資料控制項提供分頁功能。本文詳細說明 WinForm 與 WebForm 的分頁模式差異,並以 TemplatePagerField 為核心,示範如何打造類似 WinForm 的完整分頁列(首頁、上一頁、頁碼範圍、下一頁、尾頁)。
NextPreviousPagerField:上一頁/下一頁/首頁/尾頁按鈕NumericPagerField:數字頁碼TemplatePagerField:完全自訂模板(最靈活)以下程式碼示範在 TemplatePagerField 中使用 PagerTemplate 定義分頁 UI,並在 OnPagerCommand 事件處理換頁邏輯:
<asp:DataPager runat="server" ID="ContactsDataPager" PageSize="30" PagedControlID="StoresListView">
<Fields>
<asp:TemplatePagerField OnPagerCommand="TemplatePagerField_OnPagerCommand">
<PagerTemplate>
<asp:LinkButton ID="FirstButton" runat="server" CommandName="First" Text="<<"
Enabled='<%# Container.StartRowIndex > 0 %>' />
<asp:LinkButton ID="PreviousButton" runat="server" CommandName="Previous"
Text='<%# (Container.StartRowIndex - Container.PageSize + 1) & " - " & (Container.StartRowIndex) %>'
Visible='<%# Container.StartRowIndex > 0 %>' />
<asp:Label ID="CurrentPageLabel" runat="server"
Text='<%# (Container.StartRowIndex + 1) & "-" & (IIf(Container.StartRowIndex + Container.PageSize > Container.TotalRowCount, Container.TotalRowCount, Container.StartRowIndex + Container.PageSize)) %>' />
<asp:LinkButton ID="NextButton" runat="server" CommandName="Next"
Text='<%# (Container.StartRowIndex + Container.PageSize + 1) & " - " & (IIf(Container.StartRowIndex + Container.PageSize*2 > Container.TotalRowCount, Container.TotalRowCount, Container.StartRowIndex + Container.PageSize*2)) %>'
Visible='<%# (Container.StartRowIndex + Container.PageSize) < Container.TotalRowCount %>' />
</PagerTemplate>
</asp:TemplatePagerField>
</Fields>
</asp:DataPager>
Protected Sub TemplatePagerField_OnPagerCommand(ByVal sender As Object, ByVal e As DataPagerCommandEventArgs)
Select Case e.CommandName
Case "Next"
Dim newIndex As Integer = e.Item.Pager.StartRowIndex + e.Item.Pager.PageSize
If newIndex <= e.TotalRowCount Then
e.NewStartRowIndex = newIndex
e.NewMaximumRows = e.Item.Pager.MaximumRows
End If
Case "Previous"
e.NewStartRowIndex = e.Item.Pager.StartRowIndex - e.Item.Pager.PageSize
e.NewMaximumRows = e.Item.Pager.MaximumRows
Case "First"
e.NewStartRowIndex = 0
e.NewMaximumRows = e.Item.Pager.MaximumRows
End Select
End Sub
| 屬性 | 說明 |
|---|---|
Container.StartRowIndex | 目前頁面起始資料索引 (0-based) |
Container.PageSize | 每頁筆數 |
Container.TotalRowCount | 總資料筆數 |
e.NewStartRowIndex | 設定下一頁的起始索引 |
e.NewMaximumRows | 設定下一頁的最大筆數 |
完整頁面包含 ListView 顯示客戶資料、DataPager 分頁、SqlDataSource 連接 AdventureWorks 資料庫。執行後即可獲得功能完整、樣式可控的分頁體驗。
透過 TemplatePagerField 開發者可完全掌控分頁 UI 與邏輯,滿足各種客製化需求。