GridView DropDownList Pager - Raj Kaimal

GridView DropDownList Pager

This post shows you how to add a custom DropDownlist pager and pager buttons to the GridView as shown below:

gridview_dropdown_pager

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 .

Published Monday, August 14, 2006 10:18 AM by rajbk
Filed under: , , ,

Comments

# re: GridView DropDownList Pager

Raj, Real good solution, i dont know how this simple skipped my View ! Thx pointing.. Also, do u have any pointers for implementing static headers in gridview ! As soon as we put the gridview under div panel, [we have 20+ columns] any static header solutions screws up. Also the same case for Atlas update panel ? Thx, Gopi

Monday, August 14, 2006 1:02 PM by Gopinath Varadharajan

# GridView DropDownList Pager

Monday, August 14, 2006 3:14 PM by -:[web caboodle]:-

# GridView DropDownList Pager

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Monday, August 14, 2006 8:32 PM by DotNetKicks.com

# re: GridView DropDownList Pager

This is the best solution anyone can think of. Great work. Thanks a lot

Saturday, October 14, 2006 10:45 PM by Prashant Atal

# re: GridView DropDownList Pager

i got an error 'PresentationUtils doesn't exist in context'. Any idea? Thanks a lot.

Thursday, October 19, 2006 11:06 AM by amber001

# re: GridView DropDownList Pager

What is the PresentationUtils class? I cannot get my project to build with that in there. I love the concept though!

Tuesday, October 31, 2006 11:49 AM by Jon Whitehead

# re: GridView DropDownList Pager

PresentationUtils is a class you create which contains the method SetPagerStates.

Wednesday, November 01, 2006 2:41 PM by rajbk

# re: GridView DropDownList Pager

hello it's nice and useful code. but as i'm not very good in delegates and events right now i have a problem and i need to solve it quickly. that's it : what if i need to handle for example the sorting of a gridview in a separate class like u did i can't put += delegate{...} because i need the information provided by the "GridViewSortEventArgs" so my question is how to pass this information because until i tried lots of things and the sorting is not handled until i use the delegate{....} to simplify the thing what would you do if for your dropdownlist u need to use the args of its eventhandler ? it's very urgent i will be grateful for an answer sorry for my english thx in advance

Thursday, November 09, 2006 12:23 PM by Mourad

# re: GridView DropDownList Pager

unbelivably easy - thanks :o)

Monday, December 04, 2006 5:56 PM by imbehemot

# re: GridView DropDownList Pager

Great bit of code, cheers for sharing.

Tuesday, December 12, 2006 9:12 AM by Chrismogz

# re: GridView DropDownList Pager

Any solution for no postbacks and use ajax callbacks with PagerTemplate?

Sunday, December 17, 2006 4:35 AM by Gudus

# re: GridView DropDownList Pager

thanks for your code. it help me complete my homework. I hope i can give you another codes

Friday, December 22, 2006 3:30 AM by Hoai

# re: GridView DropDownList Pager

Awesome and yet simple code! it really helped me out with my YourCollegePapers.com site!  Thanks a million!

Dave

Friday, January 19, 2007 9:52 AM by You are genius!

# re: GridView DropDownList Pager

useful, simple code

cheers!

Monday, January 29, 2007 12:27 AM by plibertine

# re: GridView DropDownList Pager

Pls send this code in C#. PageIndex always gives 0.

Thanks in advance

Friday, March 16, 2007 8:51 AM by Ashish

# re: GridView DropDownList Pager

Ashish,

The code *is* in C#.

Friday, March 16, 2007 8:37 PM by rajbk

# re: GridView DropDownList Pager

tnx for this code!!

exist a method to render pagertemplate if page number is 1??

Wednesday, May 02, 2007 9:20 AM by ilbarzo

# re: GridView DropDownList Pager

Thought people would enjoy seeing the .net vbscript version of this.

Row Created Event Handler:

   Protected Sub SearchResultsGrid_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

       If e.Row.RowType = DataControlRowType.Pager Then

           utils.SetPagerButtonStates(SearchResultsGrid, e.Row)

       End If

   End Sub

Reset the Index of your grid if the user uses the Drop-down (set to the OnSelectedIndexChange property of the dropdown):

   Protected Sub setIndex(ByVal sender As Object, ByVal e As EventArgs)

       SearchResultsGrid.PageIndex = sender.SelectedIndex

   End Sub

And finally I tweaked the code a bit for SetPagerButtonStates.  I prefer to use Link buttons for style reasons, so I've changed all the dim statements to LinkButton rather than Button.

Public Shared Sub SetPagerButtonStates(ByVal gridView As GridView, ByVal gvPagerRow As GridViewRow)

       Dim pageIndex As Integer = gridView.PageIndex

       Dim pageCount As Integer = gridView.PageCount

       Dim i As Integer

       Dim btnFirst As LinkButton = gvPagerRow.FindControl("btnFirst")

       Dim btnPrevious As LinkButton = gvPagerRow.FindControl("btnPrev")

       Dim btnNext As LinkButton = gvPagerRow.FindControl("btnNext")

       Dim btnLast As LinkButton = gvPagerRow.FindControl("btnLast")

       Dim lbltotal As Label = gvPagerRow.FindControl("pagetotal")

       If gridView.PageIndex <> 0 Then

           btnFirst.Enabled = True

           btnPrevious.Enabled = True

       Else

           btnFirst.Enabled = False

           btnPrevious.Enabled = False

       End If

       If gridView.PageIndex < (gridView.PageCount) - 1 Then

           btnLast.Enabled = True

           btnNext.Enabled = True

       Else

           btnLast.Enabled = False

           btnNext.Enabled = False

       End If

       lbltotal.Text = gridView.PageCount

       Dim ddlPageSelector As DropDownList = gvPagerRow.FindControl("ddlPageSelector")

       ddlPageSelector.Items.Clear()

       For i = 1 To gridView.PageCount

           ddlPageSelector.Items.Add(i.ToString())

       Next

       ddlPageSelector.SelectedIndex = pageIndex

       gridView.SelectedIndex = pageIndex

   End Sub

Monday, June 18, 2007 3:01 PM by skril

# re: GridView DropDownList Pager

Thanks.  A great solution.

Monday, July 16, 2007 9:11 AM by Chris Williams

# re: GridView DropDownList Pager

Excellent and a very simplistic and to the point. Wish I had developers like you around. Not only the drop down list but touching upon the delegate stuff was excellent.

Tuesday, July 17, 2007 5:55 PM by Anonymous

# re: GridView DropDownList Pager

hi there...

how would i do if i want to have paging something like this:

1 2 3 4 5 6 7 .. instead of dropdownlist?

thanks

Saturday, August 11, 2007 12:24 AM by Nisar Khan

# Yurtman.net &raquo; Gridview de Dropdowlist kullanarak sayfalama

Pingback from  Yurtman.net &raquo; Gridview de Dropdowlist kullanarak sayfalama

# re: GridView DropDownList Pager

Excellent  and Thanks for give us this kind of code .

could  you give me file scrabing code .

Thursday, August 23, 2007 4:42 PM by Ankur

# re: GridView DropDownList Pager

excellent job...anyways thanx for a such nice help...

Wednesday, August 29, 2007 4:12 AM by Mehar

# re: GridView DropDownList Pager

In response to Nisar's request for 1 2 3 4 etc., I've implemented that as so:

int pageIndex = gridView.PageIndex;

int pageCount = gridView.PageCount - 1;

int pageButtonCount = gridView.PagerSettings.PageButtonCount - 1;

// We don't necessarily want page 0 to x, though. If the current page is > x / 2, then we want to centre it

int startingPage = 0;

int endingPage = pageButtonCount;

int halfButtonCount = Convert.ToInt32(pageButtonCount / 2);

if (pageIndex > halfButtonCount)

{

startingPage = pageIndex - halfButtonCount;

endingPage = pageIndex + halfButtonCount;

Literal openingDots = new Literal();

openingDots.Text = "... ";

placeholderPageSelector.Controls.Add(openingDots);

}

if (endingPage > pageCount)

{

// Obviously we don't want to link to more pages than there are given the size of the dataset

endingPage = pageCount;

}

for (int i = startingPage; i <= endingPage; i++)

{

if (i == pageIndex)

{

Literal currentPageNumber = new Literal();

currentPageNumber.Text = String.Format("{0}", i + 1);

placeholderPageSelector.Controls.Add(currentPageNumber);

}

else

{

LinkButton pageLink = new LinkButton();

placeholderPageSelector.Controls.Add(pageLink);

pageLink.Text = String.Format("{0}", i + 1);

pageLink.CommandName = "Page";

pageLink.CommandArgument = String.Format("{0}", i + 1);

}

Literal separator = new Literal();

if (i < endingPage)

{

separator.Text = ", ";

}

else if (i < pageCount)

{

separator.Text = " ...";

}

placeholderPageSelector.Controls.Add(separator);

}

Hopefully that's clear enough.

I'm interested in anyone having any suggestions as to the easiest way to save this pager template and accompanying code in, say, a User Control, so that you don't have to add it to every page. Or, for that matter, change it on every page if someone comes up with a better design.

Cheers,

Steve

Wednesday, August 29, 2007 10:36 AM by Steve O

# re: GridView DropDownList Pager

Steve,

Thanks for your help.

where do you add placeholderPageSelector?

Friday, August 31, 2007 10:09 AM by Nisar Khan

# re: GridView DropDownList Pager

does not work as expected

if i have a 5 rows its displaying me

11111

if i have 385 rows its displaying something like this:

111, 2, 3, 4, 5, 6, 7, 8, 9, 10 ...1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ...1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ...1, 2, 3, 4, 5, 6, 7, 8, 9, 10

i have added

<asp:PlaceHolder ID="placeholderPageSelector" runat="server"></asp:PlaceHolder>

Friday, August 31, 2007 10:17 AM by Nisar Khan

# re: GridView DropDownList Pager

Hi,

This was a very helpful article for me.

And it helped me a lot in my function.

Wednesday, September 05, 2007 3:56 PM by Abhishek

# re: GridView DropDownList Pager

Hi

I need to find out the current row of gridview while the items in the dropdownlist in that row get changed.Now work fine until if the above row's dropdown empty.If already above row DDL have value and I try to select the below row DDL the row values which is above selected

I used ASP.Net2.0 I include everthying,but if user came back aggain the back button problem happened

Thursday, September 27, 2007 6:14 AM by Natraj

# Gridview de Dropdowlist kullanarak sayfalama

Gridview de Dropdowlist kullanarak sayfalama

Wednesday, October 24, 2007 3:20 PM by Yurtman.net

# re: GridView DropDownList Pager

Instead of raising an event on every row, you can just add an event OnPreRender.  This way you only catch the event once rather than once per row.  The only change you need to make is in finding the controls just reference:

GridView1.TopPagerRow.FindControl()

Thursday, November 08, 2007 10:34 PM by Tom

# re: GridView DropDownList Pager

Great code.

Small problem. I turns out that with large number of pages ( I have 1300) the sequence below introduces a huge delay while navigating through pages. Apparently it takes more time to fill the combo than it takes to get the data from the DB. (I suppose the rendering takes very long)

for (int i = 1; i <= gridView.PageCount; i++)

       {

           ddlPageSelector.Items.Add(i);

       }

Regards

Tuesday, November 20, 2007 10:15 AM by mmmmmm

# re: GridView DropDownList Pager

when i use the vb code i got a syntax error saying that Name 'Utils' not decalred eventhough i hv imports system.web.utils...

can guide me

Monday, December 03, 2007 10:37 PM by dev Oneal

# re: GridView DropDownList Pager

How would you add a total recrods count to this?  My ulitimate goal is to display something like this:

Displaying records X of Y of Z total records.  

I've been able to get the X and Y, but can't get the Z.. the total records in the GridView.

Tried GridView.Rows.Count, but it doesn't work.

Tuesday, December 25, 2007 12:11 AM by GuestUser

# re: GridView DropDownList Pager

Works great and very simple to add in. Thanks!

Sunday, March 02, 2008 10:43 PM by Daniel

# re: GridView DropDownList Pager

many thansk it was so helpfull for me

Saturday, April 12, 2008 7:20 PM by ar

# re: GridView DropDownList Pager

Very Useful code thanks very much

Friday, May 16, 2008 6:24 AM by Sarawut

Leave a Comment

(required) 
(required) 
(optional)
(required)