前端標記重點
<asp:GridView ID="viewIShow" runat="server" DataSourceID="ObjectDataSource1"
AllowPaging="True" AutoGenerateColumns="False" PageSize="2"
OnRowCommand="viewIShow_RowCommand"
OnPageIndexChanging="viewIShow_PageIndexChanging"
OnDataBound="viewIShow_DataBound">
<Columns>
<asp:BoundField DataField="title" HeaderText="名稱" />
<asp:BoundField DataField="clicknum" HeaderText="播放次數" />
<asp:BoundField DataField="addtime" HeaderText="更新日期" />
<asp:TemplateField HeaderText="操作">
<ItemTemplate>
<asp:LinkButton CommandName="up" CommandArgument='<%#Eval("id") %>'>晉級</asp:LinkButton>
<asp:LinkButton CommandName="down" CommandArgument='<%#Eval("id") %>'>降級</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerTemplate>
<webdiyer:AspNetPager ID="myPage" runat="server" OnPageChanged="myPage_PageChanged" />
</PagerTemplate>
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="AUDIOSYSTEM.BLL.ishow"
SelectMethod="GetList" DataObjectTypeName="AUDIOSYSTEM.Model.ishow"
OnSelected="ObjectDataSource1_Selected">
<SelectParameters>
<asp:Parameter Name="type" DefaultValue="week" />
<asp:ControlParameter ControlID="txtStartTime" Name="start" PropertyName="Text" Type="DateTime" />
<asp:ControlParameter ControlID="txtEndTime" Name="end" PropertyName="Text" Type="DateTime" />
</SelectParameters>
</asp:ObjectDataSource>
後端核心邏輯
// 1. AspNetPager 頁碼變更 -> 同步 GridView
protected void myPage_PageChanged(object sender, EventArgs e)
{
var pagerRow = viewIShow.BottomPagerRow;
var myPage = (AspNetPager)pagerRow.Cells[0].FindControl("myPage");
viewIShow.PageIndex = myPage.CurrentPageIndex - 1; // GridView 從 0 開始
}
// 2. GridView 資料綁定完成 -> 同步 AspNetPager 狀態
protected void viewIShow_DataBound(object sender, EventArgs e)
{
var pagerRow = viewIShow.BottomPagerRow;
var myPage = (AspNetPager)pagerRow.Cells[0].FindControl("myPage");
myPage.PageSize = viewIShow.PageSize;
myPage.CurrentPageIndex = viewIShow.PageIndex + 1;
}
// 3. ObjectDataSource 查詢完成 -> 取得總筆數給 AspNetPager
protected void ObjectDataSource1_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
var pagerRow = viewIShow.BottomPagerRow;
var myPage = (AspNetPager)pagerRow.Cells[0].FindControl("myPage");
if (e.ReturnValue is DataSet ds && ds.Tables.Count > 0)
myPage.RecordCount = ds.Tables[0].Rows.Count;
else
myPage.RecordCount = 0;
}
關鍵同步點總結
| 事件 | 責任 | 關鍵屬性 |
| myPage_PageChanged | 用戶換頁 -> 設定 GridView.PageIndex | CurrentPageIndex - 1 |
| viewIShow_DataBound | GridView 綁定後 -> 更新 Pager 顯示 | PageSize, CurrentPageIndex |
| ObjectDataSource1_Selected | 查詢完成 -> 設定總筆數 | RecordCount = Rows.Count |
常見坑點
- GridView `PageIndex` 從 0 開始,AspNetPager `CurrentPageIndex` 從 1 開始,互轉必須 ±1。
- PagerTemplate 內的控制項需用 `FindControl` 取得,不可直接 `this.myPage`。
- ObjectDataSource 回傳型別需與 `SelectMethod` 簽章一致,`OnSelected` 才能正確轉型。