ASP.NET技巧:GridView控件自定义分页详解
在这里我们将用一个隐藏字段来保存这个PageIndex,即当前页码.当点击上一页时,将它的值减一,知道为0,要注意的一点这里的第一页页码是0而不是1.下面看看代码,然后我们再分析分析!
1<asp:GridView ID="NewsGrid" runat="server" AllowPaging="false" Width="100%">
2 <Columns>
3 <asp:BoundField DataField="NewsId" HeaderText="新闻ID"/>
4 <asp:HyperLinkField DataNavigateUrlFields="NewsId" DataNavigateUrlFormatString="~/Details.aspx?ID={0}"
5 DataTextField="Title" HeaderText="新闻标题" ItemStyle-Width="70%"/>
6 <asp:BoundField DataField="PostTime" HeaderText="发布时间"/>
7 <asp:CommandField HeaderText="新闻管理" ShowCancelButton="False" ShowDeleteButton="True"
8 ShowEditButton="True"/>
9 </Columns>
10 </asp:GridView>
11 <div style=" height:16px; padding-top:5px; margin-right:30px; float:right">
12 <asp:HiddenField ID="CurrentPage" runat="server" Value="0"/>
13 <asp:LinkButton ID="First" runat="server" CommandArgument="first" onclick="PagerButton_Click">首 页</asp:LinkButton>
14 <asp:LinkButton ID="Prev" runat="server" CommandArgument="prev" onclick="PagerButton_Click">上一页</asp:LinkButton>
15 <asp:LinkButton ID="Next" runat="server" CommandArgument="next" onclick="PagerButton_Click">下一页</asp:LinkButton>
16 <asp:LinkButton ID="Last" runat="server" CommandArgument="last" onclick="PagerButton_Click">尾 页</asp:LinkButton>
17 </div> CS文件中的代码:
1 protected void PagerButton_Click(object sender, EventArgs e)
2 {
3 int pageIndx = Convert.ToInt32(CurrentPage.Value);
4 int totals = NewsManager.GetNews(0, pageSize).TotalRecords;
5 int pages = (totals % pageSize) == 0 ? (totals / pageSize) : (totals / pageSize + 1);
6 string arg = ((LinkButton)sender).CommandArgument.ToString().ToLower();
7 switch (arg)
8 {
9 case "prev":
10 if (pageIndx > 0)
11 {
12 pageIndx -= 1;
13 }
14 break;
15 case "next":
16 if (pageIndx < pages - 1)
17 {
18 pageIndx += 1;
19 }
20 break;