GridView DropDownList Pager
This post shows you how to add a custom DropDownlist pager and pager buttons to the GridView as shown below:
Unlike the behavior of the default pager buttons, these buttons get disabled instead of being hidden (depending on the state of the GridView).
IMHO, buttons that remain at the same position while paging through a resultset makes a better UI (spatial memory).
The code is pretty straightforward.
Add the following pager template to your GridView.
<PagerTemplate>Goto Page
<asp:DropDownList ID="ddlPageSelector" runat="server" AutoPostBack="true">
</asp:DropDownList>
<asp:Button Text="First" CommandName="Page" CommandArgument="First" runat="server"
ID="btnFirst" />
<asp:Button Text="Previous" CommandName="Page" CommandArgument="Prev" runat="server"
ID="btnPrevious" />
<asp:Button Text="Next" CommandName="Page" CommandArgument="Next" runat="server"
ID="btnNext" />
<asp:Button Text="Last" CommandName="Page" CommandArgument="Last" runat="server"
ID="btnLast" />
</PagerTemplate>
Add a RowCreated event handler to your GridView and add the following code:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.Pager) {
PresentationUtils.SetPagerButtonStates(GridView1, e.Row, this);
}
}
Finally, add the following code to your common class (PresentationUtils in my case)
public static void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page) {
int pageIndex = gridView.PageIndex;
int pageCount = gridView.PageCount;
Button btnFirst = (Button)gvPagerRow.FindControl("btnFirst");
Button btnPrevious = (Button)gvPagerRow.FindControl("btnPrevious");
Button btnNext = (Button)gvPagerRow.FindControl("btnNext");
Button btnLast = (Button)gvPagerRow.FindControl("btnLast");
btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount - 1));
DropDownList ddlPageSelector = (DropDownList)gvPagerRow.FindControl("ddlPageSelector");
ddlPageSelector.Items.Clear();
for (int i = 1; i <= gridView.PageCount; i++) {
ddlPageSelector.Items.Add(i.ToString());
}
ddlPageSelector.SelectedIndex = pageIndex;
//Anonymous method (see another way to do this at the bottom)
ddlPageSelector.SelectedIndexChanged += delegate {
gridView.PageIndex = ddlPageSelector.SelectedIndex;
gridView.DataBind();
};
}
AFAIK, VB.net 2.0 does not support anonymous methods. Therefore, for those of you converting this code to VB.net, you will need to add the handler manually. Go to the GridView Tasks and select "Edit templates", select the PagerTemplate and double click on the DropDownList to add a index changed event handler. In the event handler, write the VB.net equivalent of this:
protected void ddlPageSelector_SelectedIndexChanged(object sender, EventArgs e) {
GridView1.PageIndex = ((DropDownList)sender).SelectedIndex;
GridView1.DataBind();
}
Related : Clickable GridView Headers .