<asp:Label ID="lblPage" runat="server" Text='<%# "第" + (((GridView)Container.NamingContainer).PageIndex + 1) + "页/共" + (((GridView)Container.NamingContainer).PageCount) + "页" %> '></asp:Label>
这句代码是显示数据供有几页,当前在第几页。我们通过((GridView)Container.NamingContainer).PageIndex来获取当前页,通过((GridView)Container.NamingContainer).PageCount来获取总页数。

<asp:LinkButton ID="lbnFirst" runat="Server" Text="首页" Enabled='<%# ((GridView)Container.NamingContainer).PageIndex != 0 %>' CommandName="Page" CommandArgument="First" ></asp:LinkButton>
这一句代码实现跳转到列表的第一页,后台代码通过响应GridView.RowCommand 事件,根据CommandName="Page"和CommandArgument="First"来定位到分页列表的第一页。GridView中的任何一个按钮被点击都会触发RowCommand 事件,我们可以通过该事件来自定义处理程序。更多的时候建议使用GridView内置的属性。下表是MSDN上对GridView内置属性的一个简单说明。
CommandName值
说明
执行分页操作。将按钮的CommandArgument属性设置为“First”、“Last”、“Next”、“Prev”或页码,以指定要执行的分页操作类型。引发和事件。

到第<asp:TextBox runat="server" ID="inPageNum"></asp:TextBox>页 <asp:Button ID="Button1" CommandName="go" runat="server" />
这段代码是实现用户自己输入页码,然后点击Button跳转的的前台代码。为了使用RowCommand 事件,我们自定义了CommandName="go",当然你也可以在这里添加CommandArgument以传递更多的信息。
前台代码就这些,下面我们介绍后台代码。gridview分页
private void BindGridView() { using (BlogDataContext bdc = new BlogDataContext()) { var artList = bdc.Blog_GetAllCommentationArticles(); Blog_GetAllCommentationArticlesResult g = new Blog_GetAllCommentationArticlesResult(); GridView1.DataSource = artList; GridView1.DataBind(); } } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { try { GridView1.PageIndex = e.NewPageIndex; BindGridView(); TextBox tb = (TextBox)GridView1.BottomPagerRow.FindControl("inPageNum"); tb.Text = (GridView1.PageIndex + 1).ToString(); } catch { } } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "go") { try { TextBox tb = (TextBox)GridView1.BottomPagerRow.FindControl("inPageNum"); int num = Int32.Parse(tb.Text); GridViewPageEventArgs ea = new GridViewPageEventArgs(num - 1); GridView1_PageIndexChanging(null, ea); } catch { } } }
GridView1_RowCommand方法,在这里是响应用户自己输入页码点击Button按钮的事件。首先获取用户输入的页码数,然后调用GridView1_PageIndexChanging方法,使GridView更新数据
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-30495-2.html
早安小王子@TFBOYS-易烊千玺