Aug 28, 2009

ASP.Net Custom Paging Control

I've been playing with GridViews for quite some time & have always wondered if there's a better way of displaying the pager at the bottom, instead of the "1 2 3 ..." that you get by default.

As it worked out, I had the reason today to look more into this for a customer request. I happened to find an article that gave code to do this. It was a decent starting point, but I didn’t like how the records displayed were numbered from 0-(count-1), but it got me going.

Here’s what two options I’m considering using:

This one uses media player type links (i.e. |< << >> >|)
<PagerTemplate>
<asp:LinkButton CommandName="Page" CommandArgument="First" ID="LinkButton1" runat="server" Style="color: white">|&lt;</asp:LinkButton>
<asp:LinkButton CommandName="Page" CommandArgument="Prev" ID="LinkButton2" runat="server" Style="color: white">&lt;&lt;</asp:LinkButton>
[Records <%= (Grid.PageIndex * Grid.PageSize)+1 %> - <%= Grid.PageIndex * Grid.PageSize + Grid.Rows.Count %> (<%= iTotalRecordCount %>)]
<asp:LinkButton CommandName="Page" CommandArgument="Next" ID="LinkButton3" runat="server" Style="color: white">&gt;&gt;</asp:LinkButton>
<asp:LinkButton CommandName="Page" CommandArgument="Last" ID="LinkButton4" runat="server" Style="color: white">&gt;|</asp:LinkButton>
</PagerTemplate>
And this one has words for First/Last as well:
<PagerTemplate>
<asp:LinkButton CommandName="Page" CommandArgument="First" ID="LinkButton1" runat="server" Style="color: white">&lt;&lt; First</asp:LinkButton>
<asp:LinkButton CommandName="Page" CommandArgument="Prev" ID="LinkButton2" runat="server" Style="color: white">&lt; Prev</asp:LinkButton>
[Records <%= (Grid.PageIndex * Grid.PageSize)+1 %> - <%= Grid.PageIndex * Grid.PageSize + Grid.Rows.Count %> (<%= iTotalRecordCount %>)]
<asp:LinkButton CommandName="Page" CommandArgument="Next" ID="LinkButton3" runat="server" Style="color: white">Next &gt;</asp:LinkButton>
<asp:LinkButton CommandName="Page" CommandArgument="Last" ID="LinkButton4" runat="server" Style="color: white">Last &gt;&gt;</asp:LinkButton>
</PagerTemplate>
One caveat, I use a variable iTotalRecordCount that is defined on the code behind:
public int iTotalRecordCount = 0;
And defined in a BindGrid() method I call on button click:
iTotalRecordCount = dataTable.Rows.Count;
Lastly, you need to implement the "OnPageIndexChanging" event:
    protected void Grid_PageIndexChanging( object sender, GridViewPageEventArgs e ) {
Grid.PageIndex = e.NewPageIndex;
BindGrid( );
}
Anyway, I hope someone out there finds this useful. :)

No comments: