Custom Paging in GridView Control

Introduction

I searched the entire web looking for tutorials about custom paging in GridView control in ASP.Net 2.0. Since GridView is relatively new to ASP.Net, most of my search returned custom paging using DataGrid Control.

To help others who have the same problem as I encountered today, here is the tutorial regarding custom paging in GridView. I hope you’ll have a great time reading my article as I have writing it.

Overview

While DataGrid requires additional coding for it’s paging, GridView control automatically supports paging by setting the PagerSettings property. This allows you to customize the appearance of the pager the the GridView automatically generates for you. You can set the mode of your PagerSetting to the following custom made selections

  1. NextPrevious - This will render a “Next Previous” Pager on your control.
  2. NextPreviousFirstLast - A set of pagination controls consisting of Previous, Next, First, and Last buttons.
  3. Numeric - Sets your pagination to a 1 2 3 4 5 ….
  4. NumericFirstLast - Numeric pagination (1 2 3 4 …) plus the first and last page anchor.

The fun part is customizing this pager based on your preference and requirements. You can achieve this by adding a PagerTemplate template.

In this article we will make a “DAO” like pager with a First, Previous, Next and Last Image Button and a DropDownList of the Page Number.

1. Using your favorite graphic editor (Photoshop), create four buttons that will serve as your icon for the First, Previous, Next and Last buttons.

2. Set your GridView control’s AllowPaging property to true.

3. Add a PagingTemplate inside your GridView and insert 4 ImageButton, 1 DropDownList and a Label controls which will serve as your First, Previous, Next, Last, Page No., and Page Picker of your pager.

<asp:GridView …>

<PagerTemplate>
        <asp:ImageButton ID="ImageButton1" runat="server"
            ImageUrl="~/images/controls/first.gif" />
        <asp:ImageButton ID="ImageButton2" runat="server"
            ImageUrl="~/images/controls/previous.gif" />

Page
        <asp:DropDownList ID="ddlPages" runat="server"
            AutoPostBack="True">
        </asp:DropDownList> of <asp:Label ID="lblPageCount"
            runat="server"></asp:Label>

<asp:ImageButton ID="ImageButton3" runat="server"
            ImageUrl="~/images/controls/next.gif" />
        <asp:ImageButton ID="ImageButton4" runat="server"
            ImageUrl="~/images/controls/last.gif" />

</PagerTemplate>

</asp:GridView>

Your pager should look like this when you render the page.

4. Add an OnDataBound Event to your GridView. This will render and populate your DropDownList (for page picker) and Label (for page count) controls. Implementation can look like this.

protected void grdListings_DataBound(Object sender, EventArgs e)
{
    GridViewRow gvrPager = grdListings.BottomPagerRow;

    if (gvrPager == null) return;

    // get your controls from the gridview
    DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
    Label lblPageCount = (Label)gvrPager.Cells[0].FindControl("lblPageCount");

    if (ddlPages != null)
    {
        // populate pager
        for (int i = 0; i < grdListings.PageCount; i++)
        {

            int intPageNumber = i + 1;
            ListItem lstItem = new ListItem(intPageNumber.ToString());

            if (i == grdListings.PageIndex)
                lstItem.Selected = true;

            ddlPages.Items.Add(lstItem);
        }
    }

    // populate page count
    if (lblPageCount != null)
        lblPageCount.Text = grdListings.PageCount.ToString();
}

5. Next, we implement an OnSelectedIndexChanged on our DropDownList to go to the selected page when a selection is made from our dropdown.

protected void ddlPages_SelectedIndexChanged(Object sender, EventArgs e)
{
    GridViewRow gvrPager = grdInvestors.BottomPagerRow;
    DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");

    grdListings.PageIndex = ddlPages.SelectedIndex;

    // a method to populate your grid
    PopulateGrid();
}

6. In order for you arrow buttons to work. We must implement an OnCommand event of your buttons. Before that we have to specify a CommandArgument properties to each of our buttons.

<asp:ImageButton ID="ImageButton1" runat="server"
    ImageUrl="~/images/controls/first.gif"
    CommandArgument="First" CommandName="Page" />
<asp:ImageButton ID="ImageButton2" runat="server"
    ImageUrl="~/images/controls/previous.gif"
    CommandArgument="Prev" CommandName="Page" />

<asp:ImageButton ID="ImageButton3" runat="server"
    ImageUrl="~/images/controls/next.gif"
    CommandArgument="Next" CommandName="Page" />
<asp:ImageButton ID="ImageButton4" runat="server"
    ImageUrl="~/images/controls/last.gif"
    CommandArgument="Last" CommandName="Page" />

7. Finally, the OnCommand event implementation.

protected void Paginate(object sender, CommandEventArgs e)
{
    // get the current page selected
    int intCurIndex = grdListings.PageIndex;

    switch (e.CommandArgument.ToString().ToLower())
    {
        case "first":
            grdListings.PageIndex = 0;
            break;
        case "prev":
            grdListings.PageIndex = intCurIndex - 1;
            break;
        case "next":
            grdListings.PageIndex = intCurIndex + 1;
            break;
        case "last":
            grdListings.PageIndex = grdListings.PageCount;
            break;
    }

    // popultate the gridview control
    PopulateGrid();
}

Summary

Customizing your GridView pager gives you flexibility and fine grain control over your grid listing. Just don’t be afraid of exploring, experimenting and playing with it to achieve the desired functionalities that you want. Happy coding.

82 Responses to “Custom Paging in GridView Control”


  1. 1 Derek Klingman

    Man you are a life saver!!! This was exactly what I was looking for. Thanks sooo much!!!

  2. 2 Chad Boulton

    Hey, why are my pager buttons in the first column of the gridView? Why does it only create one cell? I’d love to do a colspan, but gridview.BottomPagerRow is always null!? — any ideas?…

  3. 3 grminds

    A nice article.This helped me a lot while implementing custompaging.

  4. 4 Edison

    Nice and cool article,
    you make me to be a looser!

  5. 5 maggie

    it is just what i want to do these days! cool….

  6. 6 maggie

    I use objectDataSource to bind gridview control,
    can i just use:
    // popultate the gridview control
    eGridView.databind()

    but,the paging doesn’t work, any idea?

  7. 7 John

    I don’t understand which event that procedure “protected void Paginate(object sender, CommandEventArgs e)” hand for ? and What does “PopulateGrid()” do ?;

  8. 8 chakrit

    just what I’m looking for! thanks for taking the time to explain this out

  9. 9 Tim

    Hi. Very nice. Is there a way I can switch the image to a disabled one (first and previous) when I am on page one? Thanks.

  10. 10 Tim

    When does

    Protected Sub Paginate(ByVal sender As Object, ByVal e As System.EventArgs)

    get called?

  11. 11 Tim

    Hi, instead of a DropDown to select a page can a numeric pager be displayed along with the buttons in the PagerTemplate?

  12. 12 Hzaleoanodon

    Really Really good article. Cheers :)

  13. 13 Dony

    A really cool article, help me a lot….
    Thanks

  14. 14 Vince

    Hi,
    i’m newbie to asp.net, I ran few test on your code and it give me several errors.
    First, “grdlistings”, “grdInvestors”, and “populateGrid” does not exist in the current context.
    Am i missing something in the program?

    Any help would be appreciate.
    Thanks

  15. 15 Doyle

    wat about if i want the format is like this
    |> >|

  16. 16 Doyle

    1> >1

  17. 17 Doyle

    <

  18. 18 Doyle

    |< << 1234 >> <|

  19. 19 Brian Wallace

    How do I get the drop downlist to work correctly. I cannot get it to fire the SelectedIndexChanged even when I select a new item. This seems to be becuase when the page loads, there isn’t anything in the list until I dynamically create the list… If anyone has it working, I sure would like to know more about how to get that piece to work, the rest works fine.

    BTW Doyle, I was creating the a post on my blog that addressed your question when I discovered this blog, you can check out the post at: http://aspadvice.com/blogs/net_discoveries/default.aspx

  20. 20 Kostis M

    A really good article, help me a lot….

    but, if we have a large number of pages (i.e. 100 or more),
    the dropdown list I thing is not very easy to accomodate.
    I should like to see an alternate method with (say) a textbox
    or something similar.

    Thanks a lot

  21. 21 yaron

    I’m trying to use it with an update panel. How do I reference the dropdownlist control in the Triggers section?

    Thanks,

    Yaron.

  22. 22 charles

    where is the F### vB?

    and where are the individual images for the example? a fake picture of the control sucks

  23. 23 Aizal

    Thank you for the really really great article!!

  24. 24 Julio Szabo

    Thanks, this is wonderful, whith any modification, it’s work good and it’s that I was looking for.
    Thanks again.

  25. 25 Minhtv

    Can you help me?
    I’m using asp.net 1.0, i don’t have tool as athlast to support ajax. If you have , can you give me it?
    thank you!

  26. 26 Balamurugan.M

    Hai!
    Very good explanation of each and everything about paging in GridViewControl.This will be very helpful and useful to evry programmers.

  27. 27 Ryan

    Thank you writing this, it helped a lot! I wanted to mention, I’m sure most people already know this, the key words for the paging, first, prev, nex, and last are very specific and if you deviate from them it messes it up. For example, you can’t use previous as the argument . . .

    Thanks again!
    Ryan

  28. 28 Mycole

    This article was helpful, but I found that after following the directions outlined here, I couldn’t get the PagerTemplate to show up. I was trying to use Custom Paging and only was retrieving exactly the rows needed to be displayed.

    I discovered that I needed to add the following:
    gvrPager.Visible = true;

    protected void grdListings_DataBound(Object sender, EventArgs e)
    {
    GridViewRow gvrPager = grdListings.BottomPagerRow;

    if (gvrPager == null)
    return;
    gvrPager.Visible = true;

    //…..
    }

    Hopefully, I’ll save someone else a few hours.
    Mycole

  29. 29 partha

    hi,
    your code helped me a lot and i have problem can we disable those pagertemplete buttons.

    regards,
    Parth

  30. 30 Ramon Rocha

    Dear sir,

    I was converted the code for VB
    I have a problem: whenever I have, for instance, 4 lines in a page that possesses up to 5 of total, when I click in the nexr button, the pagination control disappears together with the last line of the gridview…

    Página

    de

    Protected Sub grdTabela_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles grdTabela.SelectedIndexChanged
    Dim gvrPager As GridViewRow = grdTabela.BottomPagerRow
    Dim cboPages As DropDownList = CType(gvrPager.Cells(0).FindControl(”cboPages”), DropDownList)
    grdTabela.PageIndex = cboPages.SelectedIndex
    grdTabela.DataBind()
    End Sub

    Protected Sub Paginate(ByVal sender As Object, ByVal e As CommandEventArgs)
    Dim intCurIndex As Integer = grdTabela.PageIndex
    Select Case e.CommandArgument.ToString.ToUpper
    Case “FIRST”
    grdTabela.PageIndex = 0
    Case “PREV”
    intCurIndex = intCurIndex - 1
    grdTabela.PageIndex = intCurIndex
    Case “NEXT”
    intCurIndex = intCurIndex + 1
    grdTabela.PageIndex = intCurIndex
    Case “LAST”
    grdTabela.PageIndex = grdTabela.PageCount
    End Select
    grdTabela.DataBind()
    End Sub

    Protected Sub cboPages_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim gvrPager As GridViewRow = grdTabela.BottomPagerRow
    Dim cboPages As DropDownList = CType(gvrPager.Cells(0).FindControl(”cboPages”), DropDownList)
    grdTabela.PageIndex = cboPages.SelectedIndex
    End Sub

  31. 31 Ramon Rocha

    I’m sorry by my poor english (from Brazil)

  32. 32 Someone

    Just so everyone knows, the sub “Paginate” doesn’t work. Go to

    http://blog.wekeroad.com/archive/2006/12/09/GridView-Sorting-And-Paging–My-Pain-Your-Gain.aspx

    for a complete description of a functional paging using the above concept.

  33. 33 Rishi

    It’s really a nice article and helps to reduce many lines of code when I was using Repeater control and enabling paging to it.
    I have used this article with NextPrevious option and it works fine. Now I want to have this option on top and bottom both place of the gridview. How I can achieve this? please help

    Thanks.

  34. 34 Rob

    Great article! Helped me out a lot.

    One mistake I saw:

    grdListings.PageIndex = grdListings.PageCount;

    should be

    grdListings.PageIndex = grdListings.PageCount - 1;

    the GridView probably handles it gracefully, but PageCount is zero-based.

  35. 35 Joshua

    I’m having the same problem as below. I replaced the grdListings and grdInvestors with my own gridview name but what is populateGrid()? It’s not working for me.

    Please advise!

    “Hi,
    i’m newbie to asp.net, I ran few test on your code and it give me several errors.
    First, “grdlistings”, “grdInvestors”, and “populateGrid” does not exist in the current context.
    Am i missing something in the program?

    Any help would be appreciate.
    Thanks

  36. 36 Smita

    Cool !!!!
    but i wanted alphabetic paging ?
    can that be achieved too???

  37. 37 docxy

    Very Nice. Took some modification but I finally got it top work in VB.NET.
    Thanks.

  38. 38 victoria

    Very useful code .

    Thankyou Very Much

  39. 39 Abhishek

    Hi,
    This was a very helpful article for me.
    And it helped me a lot in my function.
    Really thanks a lot . this was very descriptive and easy to understand.

  40. 40 John

    Nice work thanks… If you are planning to use the code you might need to do some minor modifications and it should work.

  41. 41 George Zhu

    Very good one, which helps me a lot.

  42. 42 Matt

    Awsome job! You are a lifesaver!

  43. 43 Shobha

    Its nice

  44. 44 Deepti

    Thank you!!!!
    Thankyou!!!

    Buddy great job!!!

    Have a great day!!!

  45. 45 Airstrike

    Where do you live? I want to come give you a kiss!

  46. 46 DanR

    I’ve been trying to paging for awhile. Starting from my MasterPage/AJAX/nStuff/CSS Friendly I got no where, but I start with your sample, and add just CSS Friendly support for GridView, paging disappears totally. Not using CSS Friendly, just copying in the adapters.

    Any suggestions would be helpful.

  47. 47 Zewaccert

    Follow these guidelines and you will build that new home with little, or no, problems. replacement window minnesota can help…

  48. 48 naisioxerloro

    Hi.
    Good design, who make it?

  49. 49 Duy Tan

    what i have to do if i want to put numeric pages behind combobox?
    thanks a lot!

  50. 50 Yasser

    Thank you very much it is a great article

    But i can add code :

    In Event protected void GridView1_DataBound(object sender, EventArgs e)
    we can add this code

    //– For First and Previous ImageButton
    if (GridView1.PageIndex == 0)
    {
    //((ImageButton)GridView1.BottomPagerRow.FindControl(”btnFirst”)).Enabled = false;
    //((ImageButton)GridView1.BottomPagerRow.FindControl(”btnFirst”)).Visible = false;

    //((ImageButton)GridView1.BottomPagerRow.FindControl(”btnPrev”)).Enabled = false;
    //((ImageButton)GridView1.BottomPagerRow.FindControl(”btnPrev”)).Visible = false;

    //— OR —\\
    ImageButton btnFirst = (ImageButton)row.Cells[0].FindControl(”btnFirst”);
    ImageButton btnPrev = (ImageButton)row.Cells[0].FindControl(”btnPrev”);
    btnFirst.Visible = false;
    btnPrev.Visible = false;

    }

    //– For Last and Next ImageButton
    if (GridView1.PageIndex+1 == GridView1.PageCount)
    {
    //((ImageButton)GridView1.BottomPagerRow.FindControl(”btnLast”)).Enabled = false;
    //((ImageButton)GridView1.BottomPagerRow.FindControl(”btnLast”)).Visible = false;

    //((ImageButton)GridView1.BottomPagerRow.FindControl(”btnNext”)).Enabled = false;
    //((ImageButton)GridView1.BottomPagerRow.FindControl(”btnNext”)).Visible = false;

    //— OR —\\
    ImageButton btnLast = (ImageButton)row.Cells[0].FindControl(”btnLast”);
    ImageButton btnNext = (ImageButton)row.Cells[0].FindControl(”btnNext”);
    btnLast.Visible = false;
    btnNext.Visible = false;
    }

    Regards,
    Yasser Zaid

  51. 51 AjAs

    Thanks
    We had used your code and it is working well . Before trying this we had used following code it is also nice one Please check

    <asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors]”
    ConnectionString=”" />

    Thanks and Regards
    Ashish and Ajay

  52. 52 Manoj Paul

    great article…… I really like your way of explaination.

  53. 53 Adrian

    Great article. But why Paginate rutine is executed ?
    It even work even the name Paginate is changed with something else, like Abc for example.

    So (per VB Example)

    Protected Sub Abc(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim CurrentIndex As Integer = GridView1.PageIndex
    Dim StrVal As String = e.ToString.ToLower
    Select Case StrVal
    Case “first”
    CurrentIndex = 0
    Case “prev”
    CurrentIndex = CurrentIndex - 1
    Case “next”
    CurrentIndex = CurrentIndex + 1
    Case “last”
    CurrentIndex = GridView1.PageCount
    End Select

    works too !!!

    thx

  54. 54 Bhavesh

    hello,

    I can not get it to fire selectedindexchanged event for the ddlpages dropdownlist box becuase that control is included in Pager Template portion of the Gridview.

    Can anybody guide me in this matter?

    Thanks,
    B

  55. 55 Iqbal Mahar

    For Bhavesh

    U simply go to ur edit templet for pager and doubble clik the dropdown u will be able to get the required event

  56. 56 Gren

    Actually, I had a similar problem getting the SelectedIndexChanged event to fire because of the way I am binding to the datasource. I wired it up correctly, it just wasn’t recognizing my input. So, instead, I used the OnUnload event.

  57. 57 Gren

    BTW… I also got it to work with the SelectedIndexChanged event. However, to do so I had to attach the GridView to an ObjectDataSource (I assume a SQLDataSource would have also worked).

    Previously, I was filling it with an external class. I believe this threw off the order in which the events were being fired, so the SelectedIndexChanged event was never actually occurring.

  58. 58 Jeremy

    The VB code is actually fairly straight foward. A couple of comments:

    1) I don’t know if I missed it from translating the orginal C# code, but I didn’t see where the “Paginate” routine updated the content of the dllPages control to show the current page. I added that to my code below.

    2) As noted in one of the comments above the default handler for the dllPages_SelectedtIndexChanged is created when you double-click the drop down control in the pager template for the grid control.

    3) If you want the page control in the top position of the gridview you will need to use the TopPageRow collection.

    4) If you want to have the pager in both the top and the bottom positions. How do you determine which of the ddlPages drop downs was selected? When both positions are active there are 2 instantiations of the ddlPages control. From some quick experiements I noted that the 2 controls do not automatically synchronize values.

    Anyway here in the VB code:

    Protected Sub GridView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.DataBound
    ‘ Define variables
    Dim ddl As DropDownList
    Dim lbl As Label

    ‘ Make certain there are pages/rows to display
    If (GridView1.PageCount > 0) Then
    ‘ Get the controls from the gridview for the botton pager row
    ddl = GridView1.BottomPagerRow.Cells(0).FindControl(”ddlPages”)
    lbl = GridView1.BottomPagerRow.Cells(0).FindControl(”lblPageCount”)

    ‘ Clear and populate the ddl control
    ddl.Items.Clear()
    For counter = 1 To GridView1.PageCount
    ddl.Items.Add(counter.ToString)
    If (GridView1.PageIndex = counter - 1) Then
    ddl.SelectedItem.Value = counter - 1
    ddl.SelectedValue = counter
    End If
    Next

    ‘ Set the total pages content
    lbl.Text = GridView1.PageCount.ToString
    End If
    End Sub

    Protected Sub Paginate(ByVal sender As Object, ByVal e As System.EventArgs)
    ‘ Get the current page selected
    Dim intCurIndex As Integer
    Dim ddl As DropDownList

    ‘ Get the current index
    intCurIndex = GridView1.PageIndex

    ‘ Reset the page
    Select Case (e.ToString.ToLower)
    Case “first” : GridView1.PageIndex = 0
    Case “prev” : GridView1.PageIndex = intCurIndex - 1
    Case “next” : GridView1.PageIndex = intCurIndex - 1
    Case “last” : GridView1.PageIndex = GridView1.PageCount
    End Select

    ‘ Reset the drop down value
    ddl = GridView1.BottomPagerRow.Cells(0).FindControl(”ddlPages”)
    ddl.SelectedValue = GridView1.PageIndex + 1
    End Sub

    Protected Sub ddlPages_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    ‘ Define variqbles
    Dim ddl As DropDownList

    ‘ Get the contents of the drop down and set it into the page index
    ddl = GridView1.BottomPagerRow.Cells(0).FindControl(”ddlPages”)
    GridView1.PageIndex = ddl.SelectedIndex

    ‘ Execute the current search
    ExecuteSearch()
    End Sub

  59. 59 Janarthanan

    Thanks.. Good Code, It works fine…

  60. 60 Mukesh

    Really a Gud atrtical , i appriciate ur work !!!

    to make Pageinate works.
    you have to add Oncommand in ur Image buttons
    like i have added below

  61. 61 Mukesh

    OnCommand=”Paginate”

  62. 62 Suresh.S

    Plz.. Help to me.. Acuallly This al the codes are working very well but the problem is, When i press the Previous button,the prolem is araise that is When the PageIndex reach 0,if we press the previous botton mean the error will araise and How to set true / false for enable and visible property for GridView Pagination image.Actuallly this code is not work.So plz help to me..

  63. 63 Balaji

    Execellent, only error is OnCommand=”Paginate”. But how to implement GridView1.SelectedIndexChanged event when we click on the pagination number 1 2 3 4 5 6 >> …. How will we get the value in the event method when user clicks some number below the gridview.

    -Balaji k n

  64. 64 Krishna Chaitanya

    Hi,
    u r c# code is excellent,
    but instead of Dropdownlist i want numeric values like
    First Previous 123456…… Next Last
    like that i want can u please help me
    Thank u!!!!

  65. 65 Felix

    Hi!
    Very good code!
    The paging works great with “first”, “prev”, “next” and “last” buttons and the dropdown change when I click on them.
    But number 5: “OnSelectedIndexChanged on DropDownList to go to the selected page when a selection is made from our dropdown”
    it’s never reached. =(
    I select any page in dropdownlist, and after postback the selection in the gridview doesn’t change the page.
    Why? Any idea?

  66. 66 Anung

    Buddy, this article really helps me a lot. thanks so much.. :)

  67. 67 The Big Bollocks

    good articel

    Thanks to Mukesh for the oncommand=’prognate’ fix’

  68. 68 Vivek

    Thanxs dear your code work’s great :)

  69. 69 arun

    Thanks, very nice.

  70. 70 Rolo

    Hi,
    thanxs for this work.
    After reading all the comments in this post I got my custom paging working. Here is a summary:

    aspx:

    Seite

    von

    ————————-
    cs:
    ///
    /// when page is changed by dropdown
    ///
    ///
    ///
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
    GridViewRow gvrPager = grdvwCompanies.BottomPagerRow;
    DropDownList ddlPages =(DropDownList)gvrPager.Cells[0].FindControl(”ddlPages”);

    grdvwCompanies.PageIndex = ddlPages.SelectedIndex;

    // populate gridView
    DoCompanySearch(searchTerm);
    }

    ///
    /// when page is changed by clicking pager arrows
    ///
    ///
    ///
    void grdvwCompanies_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
    GridViewRow gvrPager = grdvwCompanies.BottomPagerRow;
    DropDownList ddlPages =(DropDownList)gvrPager.Cells[0].FindControl(”ddlPages”);
    grdvwCompanies.PageIndex = ddlPages.SelectedIndex;

    // populate gridView
    DoCompanySearch(searchTerm);
    }

    ///
    /// method for OnCommand in imagebutton
    ///
    ///
    ///
    protected void TurnThePage(object sender, CommandEventArgs e)
    {
    // get the current page selected
    int intCurIndex = grdvwCompanies.PageIndex;

    switch (e.CommandArgument.ToString().ToLower())
    {
    case “first”:
    grdvwCompanies.PageIndex = 0;
    break;
    case “prev”:
    grdvwCompanies.PageIndex = intCurIndex - 1;
    break;
    case “next”:
    grdvwCompanies.PageIndex = intCurIndex + 1;
    break;
    case “last”:
    grdvwCompanies.PageIndex = grdvwCompanies.PageCount;
    break;
    }

    // populate gridView
    DoCompanySearch(searchTerm);
    }

    ///
    /// event when data are bound to gridview
    ///
    ///
    ///
    void grdvwCompanies_DataBound(object sender, EventArgs e)
    {
    GridViewRow gvrPager = grdvwCompanies.BottomPagerRow;

    if (gvrPager == null) return;
    gvrPager.Visible = true;
    // get controls from the gridview
    DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl(”ddlPages”);
    Label lblPageCount = (Label)gvrPager.Cells[0].FindControl(”lblPageCount”);

    if (ddlPages != null)
    {
    // populate pager
    for (int i = 0; i < grdvwCompanies.PageCount; i++)
    {
    int intPageNumber = i + 1;
    ListItem lstItem = new ListItem(intPageNumber.ToString());

    if (i == grdvwCompanies.PageIndex)
    lstItem.Selected = true;

    ddlPages.Items.Add(lstItem);
    }
    }

    // populate page count
    if (lblPageCount != null)
    lblPageCount.Text = grdvwCompanies.PageCount.ToString();

    //– For First and Previous ImageButton
    if (grdvwCompanies.PageIndex == 0)
    {
    ((ImageButton)grdvwCompanies.BottomPagerRow.FindControl(”btnFirst”)).Enabled = false;
    ((ImageButton)grdvwCompanies.BottomPagerRow.FindControl(”btnPrevious”)).Enabled = false;
    }

    //– For Last and Next ImageButton
    if (grdvwCompanies.PageIndex+1 == grdvwCompanies.PageCount)
    {
    ((ImageButton)grdvwCompanies.BottomPagerRow.FindControl(”btnLast”)).Enabled = false;
    ((ImageButton)grdvwCompanies.BottomPagerRow.FindControl(”btnNext”)).Enabled = false;
    }
    }

  71. 71 Rolo

    Please add this aspx-code to my latest comment:

    Seite

    von

  72. 72 Bijay Mandal

    Code provided is excellent

  73. 73 Aki

    I guess the Paginate need some tweak. Here is my code and it works fine. In the original code of Paginate, the Previous button will generate error when it goes beyond Index 0.

    My code is :

    protected void Paginate(object sender, CommandEventArgs e)
    {
    // get the current page selected
    int intCurIndex = grdChild.PageIndex;

    switch (e.CommandArgument.ToString().ToLower())
    {
    case “first”:
    grdChild.PageIndex = 0;
    break;
    case “prev”:
    if (intCurIndex > 0)
    grdChild.PageIndex = intCurIndex - 1;
    break;
    case “next”:
    if (intCurIndex < grdChild.PageCount - 1)
    grdChild.PageIndex = intCurIndex + 1;
    break;
    case “last”:
    grdChild.PageIndex = grdChild.PageCount - 1;
    break;
    }

    // popultate the gridview control
    getDatasource();
    }

    Also, in the aspx page add the folling in the 4 page buttons: OnCommand=”Paginate”.

  74. 74 ashish

    really a very good article.

    but here i need to populate a popup grid with paging functionality without any server side image button control..

    can anybody make help in this regard or suggestions??

  75. 75 Sandeep Singh , Kuwait

    Hey Hi Man,
    Really good articals which i was searching. you did a good job keep it continue to help another guys. one more thing can i show this type paging in top and bottom of gridview i am trying it and its going on but my dropdown is not filled with my page numbers

    suggest me if you have any solution

    Thanks

  76. 76 nicholas barnaby

    Thank you so much. This really helped me a whole bunch.

  77. 77 Marco Alvarez

    Excelent Work, my friend.

    tnks from Chile

  78. 78 Happy camper

    I think that when number of records will be less then size of the page then BottomPagerRow will be not visible, isn’t it?

  79. 79 Mike Sullivan

    Thanks for the great post. It has been a big help in my gridview pagers. I was able to use Top and Bottom pager with page dropdown control handled by this code in the handler:

    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
    // Cast the sender to a Dropdown list and get selectedIndex from that
    // (then we don’t need to worry if it is coming from top or bottom
    // pager dropdown)
    grdvwCompanies.PageIndex = ((DropDownList)sender).SelectedIndex;
    }

  80. 80 Chandralekha.N.S

    Thank You!! this code helped me :)
    Regards

  1. 1 Custom Paging in GridView Control « bùbù daddi
  2. 2 Custom Paging with Gridview « Yasserzaid’s Weblog

Leave a Reply