使用GridView控件时,我们经常遇到的一个问题就是数据的分页问题。GridView控件内置了几种分页的样式,但这些样式比较简单,而且不是很美观。那么如何自定义GridView控件的分页样式呢?这里,我们就要使用GridView控件的 PagerTemplate 了。先看一下代码吧!
Code
1<PagerTemplate>
2<br/>
3<asp:LabelID="lblPage"runat="server"Text='<%#"第"+(((GridView)Container.NamingContainer).PageIndex+1)+"页/共"+(((GridView)Container.NamingContainer).PageCount)+"页"%>'></asp:Label>
4<asp:LinkButtonID="lbnFirst"runat="Server"Text="首页"Enabled='<%#((GridView)Container.NamingContainer).PageIndex!=0%>'CommandName="Page"CommandArgument="First"></asp:LinkButton>
5<asp:LinkButtonID="lbnPrev"runat="server"Text="上一页"Enabled='<%#((GridView)Container.NamingContainer).PageIndex!=0%>'CommandName="Page"CommandArgument="Prev"></asp:LinkButton>
6<asp:LinkButtonID="lbnNext"runat="Server"Text="下一页"Enabled='<%#((GridView)Container.NamingContainer).PageIndex!=(((GridView)Container.NamingContainer).PageCount-1)%>'CommandName="Page"CommandArgument="Next"></asp:LinkButton>
7<asp:LinkButtonID="lbnLast"runat="Server"Text="尾页"Enabled='<%#((GridView)Container.NamingContainer).PageIndex!=(((GridView)Container.NamingContainer).PageCount-1)%>'CommandName="Page"CommandArgument="Last"></asp:LinkButton>
8<br/>
9</PagerTemplate>
在这段代码中,第3行代码定义了当前页和总页数的信息,显示样式为“第1页/共5页”。4-7行代码分别定义了“首页”、“上一页”、“下一页”和“尾页”的样式。然后,我们看一下运行的结果吧!
这样就好看多了吧!而且简单明了!
另外,使用分页时还有注意一点:如果你的数据源是使用诸如ObjectDataSource之类的话,不需要做过多的设置,就可以工作的很好。但如果你的数据源是在程序中动态创建的话,则还要在pageIndexChanging和PageIndexChanged事件处理程序中稍作处理,否则会抛出异常!
举个例子:
Code
1protectedvoidPage_Load(objectsender,EventArgse)
2{
3if(!string.IsNullOrEmpty(this.Request.QueryString["key"]))
4{
5KeyStr=Server.UrlDecode(this.Request.QueryString["key"].ToString());
6}
7
8if(!IsPostBack)
9{
10BindResource();
11}
12
13}
14
15privatevoidBindResource()
16{
17resources=Resource.GetResourcesByTitle(KeyStr);
18
19if(resources!=null)
20{
21this.gvwResources.DataSource=resources;
22this.gvwResources.DataBind();
23}
24
25this.lbltext.Text=KeyStr;
26}
这个例子中,gvwResources是一个GridView类的实例,我们在Page_Load事件处理程序中为其创建了一个List<Resources>类型的数据源resources。此时,我们就需要对gvwResources对象的PageIndexChanging和PageIndexChanged事件进行处理。代码如下:
Code
1protectedvoidgvwResources_PageIndexChanging(objectsender,GridViewPageEventArgse)
2{
3gvwResources.PageIndex=e.NewPageIndex;
4}
5protectedvoidgvwResources_PageIndexChanged(objectsender,EventArgse)
6{
7BindResource();
8}
在PageIndexChanging事件处理程序中,将要显示的新页的值赋给gvwResources的PageIndex属性,在PageIndexChanged事件处理程序中,则将数据源重新绑定到gvwResources对象上。这样,自定义的分页按钮就能很好的工作了!
2
0
0
长按二维码向我转账
受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。
阅读
好看
已推荐到看一看
你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
取消
分享想法到看一看
确定
最多200字,当前共字
微信扫一扫
关注该公众号