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.

Read the full article…

About these ads

85 Comments

  1. Derek Klingman said

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

  2. Chad Boulton said

    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. grminds said

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

  4. Edison said

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

  5. maggie said

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

  6. maggie said

    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. John said

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

  8. chakrit said

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

  9. Tim said

    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. Tim said

    When does

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

    get called?

  11. Tim said

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

  12. Hzaleoanodon said

    Really Really good article. Cheers :)

  13. Dony said

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

  14. Vince said

    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. Doyle said

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

  16. Doyle said

    1> >1

  17. Doyle said

    <

  18. Doyle said

    |< << 1234 >> <|

  19. 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. Kostis M said

    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. yaron said

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

    Thanks,

    Yaron.

  22. charles said

    where is the F### vB?

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

  23. Aizal said

    Thank you for the really really great article!!

  24. Julio Szabo said

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

  25. Minhtv said

    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. Hai!
    Very good explanation of each and everything about paging in GridViewControl.This will be very helpful and useful to evry programmers.

  27. Ryan said

    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. Mycole said

    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. partha said

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

    regards,
    Parth

  30. Ramon Rocha said

    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. Ramon Rocha said

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

  32. Someone said

    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. Rishi said

    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. Rob said

    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. Joshua said

    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. Smita said

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

  37. docxy said

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

  38. victoria said

    Very useful code .

    Thankyou Very Much

  39. Abhishek said

    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. John said

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

  41. George Zhu said

    Very good one, which helps me a lot.

  42. Matt said

    Awsome job! You are a lifesaver!

  43. Shobha said

    Its nice

  44. Deepti said

    Thank you!!!!
    Thankyou!!!

    Buddy great job!!!

    Have a great day!!!

  45. Airstrike said

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

  46. DanR said

    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. Zewaccert said

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

  48. naisioxerloro said

    Hi.
    Good design, who make it?

  49. Duy Tan said

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

  50. Yasser said

    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. AjAs said

    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. Manoj Paul said

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

  53. Adrian said

    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. Bhavesh said

    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. Iqbal Mahar said

    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. Gren said

    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. Gren said

    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. Jeremy said

    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. Janarthanan said

    Thanks.. Good Code, It works fine…

  60. Mukesh said

    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. Mukesh said

    OnCommand=”Paginate”

  62. Suresh.S said

    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. Balaji said

    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. 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. Felix said

    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. Friday said

    the PopulateGrid();method was not defined is that an omission or we are required to do that ourselves.

    Thank you.

  67. Anil said

    When i select a page from dropdownlist(ddlpages) then it show blank page.
    why?anyone help me?

  68. Ajit Kumar said

    Cutomized paging is not working properly.

  69. Ajit Kumar said

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    LoadGridViewData();
    }
    }

    protected void LoadGridViewData()
    {
    SqlConnection con = new SqlConnection(connectionString);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = “GetEmployeeDetails”;
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(“@PageIndex”, SqlDbType.Int).Value = GridView1.PageIndex + 1;
    cmd.Parameters.Add(“@PageSize”, SqlDbType.Int).Value = GridView1.PageSize;
    SqlParameter sqlParameter = cmd.Parameters.Add(“@totalRows”, SqlDbType.Int);
    sqlParameter.Direction = ParameterDirection.Output;

    da.SelectCommand = cmd;
    DataTable dt = new DataTable();
    da.Fill(dt);

    GridView1.DataSource = dt;
    GridView1.DataBind();

    if (cmd.Parameters["@totalRows"].Value != null)
    {
    totalRows = (Int32)cmd.Parameters["@totalRows"].Value;
    }

    int currentPageIndex = GridView1.PageIndex + 1;

    lblCurrentPage.Text = currentPageIndex.ToString();

    lblTotalPages.Text = CalculateTotalPages(totalRows).ToString();
    }

    private int CalculateTotalPages(int totalRows)
    {
    int result = totalRows / GridView1.PageSize;
    int totalPages = result;
    return totalPages;
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
    GridView1.PageIndex = e.NewPageIndex;
    LoadGridViewData();
    }

    protected void Paginate(object sender, CommandEventArgs e)
    {
    switch (e.CommandName)
    {
    case “Previous”:
    GridView1.PageIndex = GridView1.PageIndex – 1;
    break;

    case “Next”:
    GridView1.PageSize = GridView1.PageIndex + 1;
    break;
    }

    LoadGridViewData();
    }
    protected void GridView1_DataBound(object sender, EventArgs e)
    {
    if (GridView1.PageIndex == 0)
    {
    ((Button)GridView1.BottomPagerRow.FindControl(“btnPrevious”)).Enabled = true;
    ((Button)GridView1.BottomPagerRow.FindControl(“btnNext”)).Enabled = true;
    }
    }

  70. bhawana said

    hi all,
    plz tall me how we access value from gridview cell.

  71. koy_chamnap said

    Hey, tell me if you have any approach of this problem. I have been working with gridview with wizard of “Custom Paging in GridView Control”. It work better ,but I respectively wanna change from “paging linkbutton” that are at the “buttom of gridview control” to position in “gridview footer” ? ! . And I ask you whether or not it is possible to put “background image” for “pager of gridview control”. (Norton ,Cambodia)

  72. Walter said

    Using ASP.net and C# web page. I made a search that organizes Data grid, but I cant get it so if theres multiple pages of the same data that when i click to another link it sticks with the search criteria instead of reseting and going to page X of the WHOLE thing

  73. Cool said

    Well, guys,

    any one know, how to get the total number of pages ie.e i wan to show
    page: 3/9 in the gridview . i have the next previous buttons, but i also want to show the page number.

    any one can share his thoughts.

    sheers

  74. Catherine said

    Jeremy,

    Thank you VERY much for the VB code.

  75. James said

    The link doesn’t work anymore

  76. James said

    Please update the link

  77. evilripper said

    LoL if I click “Read full…” the blog go in exception!! :-D

    Fatal error: Call to undefined function wp() in /home/kikocom/public_html/wp-blog-header.php on line 13

  78. how to use paging in gridview control in c# and asp.net

  79. Deepali said

    Read full article link is not working.

  80. ErTr said

    click for cache of broken link..

    http://209.85.229.132/search?q=cache:http://www.kiko-santos.com/2006/05/custom-paging-in-gridview-control/

  81. Aaron said

    Your link doesn’t work anymore…please update…

  82. Link not functional anymore

  83. ErTr said

    guys focus on sql paging.. its little hard to understand but you wil get the exactly what u want from the sql and dont need to struggle this listview, repeater bla bla craps.. its design is depends only you also.. search for sql rownumber u will love it..

  84. shailesh said

    hi friends,
    can any one give the code of
    custom gridview paging with

    first prev 123456 next last

    type of format, i have searched the entire site but not got any thing,this site link is not working,

    friends please help me.

    Thanks

  85. shailesh said

    hi friends,
    can any one give the code of
    custom gridview paging with

    first prev 123456 next last

    type of format, i have searched the entire site but not got any thing,this site link is not working,

    friends please help me.
    shailesh@seologistics.com
    Thanks

RSS feed for comments on this post

Comments are closed.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: