Some Tips and Tricks while Using ASP.NET GridView Paging

Posted by: Suprotim Agarwal , on 12/16/2008, in Category ASP.NET
Views: 161964
Abstract: In this article, we will see some tips and tricks while using the paging feature of the ASP.NET GridView control.
Some Tips and Tricks while Using ASP.NET GridView Paging
 
In this article, we will see some tips and tricks while using the paging feature of the ASP.NET GridView control. To get started with the tips, I have set up a simple GridView that binds to some data using a SQLDataSource. The mark up looks like this:
   <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AllowPaging="true" AutoGenerateColumns="false" DataKeyNames="ProductID" DataSourceID="SqlDataSource1">
                <Columns>
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" ReadOnly="true" SortExpression="ProductName" />
                <asp:BoundField DataField="QuantityPerUnit" HeaderText="Qty" ReadOnly="true" SortExpression="QuantityPerUnit" />
                <asp:BoundField DataField="UnitPrice" HeaderText="PricePerUnit" ReadOnly="true" SortExpression="UnitPrice" />
                <asp:BoundField DataField="UnitsInStock" HeaderText="StockQty" ReadOnly="true" SortExpression="UnitsInStock" />
                <asp:BoundField DataField="CategoryName" HeaderText="Category" ReadOnly="true" SortExpression="CategoryName" />
                </Columns>
            </asp:GridView>
            
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [CategoryName] FROM [Alphabetical list of products]">
      </asp:SqlDataSource>
        </div> 
    </form>
In your web.config, add a connection string as shown below:
<connectionStrings>
      <add name="NorthwindConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Let’s see some handy tips while using the paging mechanism in a GridView Control. The paging is displayed when the ‘AllowPaging’ property is set to ‘True’ in a GridView.
Tip 1: Change the style of the selected page or highlight the current page in the GridView Pager control
A simple way is to use CSS as shown below. The <PagerStyle> is set to a css class which modifies the style of the pager:
<head runat="server">
    <title></title>
       <style type="text/css">   
              .cssPager span { background-color:#4f6b72; font-size:18px;}    
        </style>
</head>
<asp:GridView ID="GridView1" runat="server" AllowPaging="true" AutoGenerateColumns="false" DataKeyNames="ProductID" DataSourceID="SqlDataSource1">
    <PagerStyle CssClass="cssPager" />
...
The output is as shown below, with the style set for the current page.
Tip 1
 
Tip 2: How to increase the spacing between the ASP.NET GridView Pager Numbers
One simple way is to use CSS again. Observe how we have set a cssClass to the PagerStyle, similar to what we saw in Tip 1, and are increasing the padding for the <td>:
<head runat="server">
    <title></title>
       <style type="text/css">           
             
              .cssPager td
            {
                  padding-left: 4px;     
                  padding-right: 4px;    
              }
        </style>
</head>
<asp:GridView ID="GridView1" runat="server" AllowPaging="true" AutoGenerateColumns="false" DataKeyNames="ProductID" DataSourceID="SqlDataSource1">
    <PagerStyle CssClass="cssPager" />
...
The output looks similar to the following with the increased space between the page number display:
Tip 2
 
Tip 3: Display GridView Paging even for a single page
If we change the query of the SQLDataSource to “SELECT TOP 10 [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [CategoryName] FROM [Alphabetical list of products]” we get only 10 rows of data. If you view the application, you will observe that there isn’t a pager displayed, since the number of pages displayed is just one(remember that the pagesize is set to 10). In order to display the pager row even for one page, use this code in the PreRender event of the GridView which sets the visibility of the BottomPagerRow to true.
C#
    protected void GridView1_PreRender(object sender, EventArgs e)
    {
        GridView gv = (GridView)sender;
        GridViewRow gvr = (GridViewRow)gv.BottomPagerRow;
        if (gvr != null)
        {
            gvr.Visible = true;
        }      
    }
VB.NET
      Protected Sub GridView1_PreRender(ByVal sender As Object, ByVal e As EventArgs)
            Dim gv As GridView = CType(sender, GridView)
            Dim gvr As GridViewRow = CType(gv.BottomPagerRow, GridViewRow)
            If gvr IsNot Nothing Then
                  gvr.Visible = True
            End If
      End Sub
 
Tip 4: Add a Label Control at the GridView footer to display page count
The first step is to set the ‘ShowFooter’ property of the GridView to ‘true’
Then in the GridView1_RowDataBound, add the following code:
C#
   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[0].Text = "Page " + (GridView1.PageIndex + 1) + " of " + GridView1.PageCount;
        }
    }
VB.NET
   Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
            If e.Row.RowType = DataControlRowType.Footer Then
                  e.Row.Cells(0).Text = "Page " & (GridView1.PageIndex + 1) & " of " & GridView1.PageCount
            End If
   End Sub
The result is displayed below – the blue colored block with the page count, showing Page 4 of 7.
Tip 4
 
Tip 5: Create a custom pager template with paging using a DropDownList control
Instead of using the built in Paging UI, if you want to define your own UI, use the <PagerTemplate>.
In this sample, we will keep a dropdownlist control to select pages instead of the default pager row UI. We will navigate pages of the GridView using the dropdownlist.
Add a <PagerTemplate> to the GridView as shown below:
 <asp:GridView ID="GridView1" runat="server" AllowPaging="true" AutoGenerateColumns="false"
            DataKeyNames="ProductID" DataSourceID="SqlDataSource1"
ShowFooter="False" OnDataBound="GridView1_DataBound">                              
                 <PagerTemplate>
                  <table width="100%">                   
                    <tr>                       
                        <td style="width:70%">
                            <asp:DropDownList ID="ddlPaging" runat="server" AutoPostBack="true"
                            OnSelectedIndexChanged="ddlPaging_SelectedIndexChanged" />
                        </td>
                    </tr>
                  </table>
                </PagerTemplate>
If you observe, we have added the OnDataBound event to the GridView. This is where we populate the DropDownList control with page data as shown below:
C#
   protected void GridView1_DataBound(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)GridView1.BottomPagerRow.Cells[0].FindControl("ddlPaging");
            
        for (int cnt = 0; cnt < GridView1.PageCount; cnt++)
        {
            int curr = cnt + 1;
            ListItem item = new ListItem(curr.ToString());
            if (cnt == GridView1.PageIndex)
            {
                item.Selected = true;
            }
 
            ddl.Items.Add(item);
 
        }
    }
VB.NET
   Protected Sub GridView1_DataBound(ByVal sender As Object, ByVal e As EventArgs)
            Dim ddl As DropDownList = CType(GridView1.BottomPagerRow.Cells(0).FindControl("ddlPaging"), DropDownList)
 
            For cnt As Integer = 0 To GridView1.PageCount - 1
                  Dim curr As Integer = cnt + 1
                  Dim item As New ListItem(curr.ToString())
                  If cnt = GridView1.PageIndex Then
                        item.Selected = True
                  End If
 
                  ddl.Items.Add(item)
 
            Next cnt
   End Sub
Since the paging is now to be done using the DropDownList, we need a mechanism where the pageindex of the GridView is set, whenever the user selects a item in the DropDownList control. We need to handle the OnSelectedIndexChanged for this purpose.
C#
    protected void ddlPaging_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)GridView1.BottomPagerRow.Cells[0].FindControl("ddlPaging");
        GridView1.PageIndex = ddl.SelectedIndex;
    }
VB.NET
      Protected Sub ddlPaging_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            Dim ddl As DropDownList = CType(GridView1.BottomPagerRow.Cells(0).FindControl("ddlPaging"), DropDownList)
            GridView1.PageIndex = ddl.SelectedIndex
      End Sub
Shown below is the output:
Tip 5
This tip was based on this excellent example on the MSDN site.
Tip 6: How to do GridView Paging using a Slider
 
Well those were some tips associated with GridView paging. In one of the forthcoming articles, we will cover some more, especially around creating specific custom paging  UI. I hope this article was useful and I thank you for viewing it. 
If you liked the article,  Subscribe to my RSS Feed or Subscribe Via Email
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Anand on Thursday, December 18, 2008 11:50 PM
Yah. Very Good. Very useful for this coding. But i need How many types of grid view EVENTS are there in ASP>NET grid. Pls
Comment posted by venkat.k.v on Monday, December 29, 2008 1:52 AM
This Is verry Verry Usefull To Us(learners).Many Many Thanks To You.
Comment posted by SVK on Tuesday, January 27, 2009 12:51 AM
i used the above code but giving me error object reference not set

not able to understand which object.
instead i used this , no error but on change of the page no gridvalues not chnaging and the dropdown values chnages back to the first

how do i rectify

Protected Sub drpdown_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        ' Jump to the specified page

        GridView1.PageIndex = Convert.ToInt32(drpdown.SelectedIndex)
        MsgBox("selected value= " & drpdown.SelectedIndex)
        GridView1.DataBind()


in GridView1_DataBound event populated the drpdwn with the no of pages
Comment posted by Suprotim Agarwal on Tuesday, January 27, 2009 1:37 AM
SVK: Make sure you have set ShowFooter="False" if you are using my sample

With the code you have posted, the selectedindex will always be the first item since a postback occurs and the control is recreated.
Comment posted by TheDirtyBird on Wednesday, February 4, 2009 8:19 AM
I like the highlight paging feature.
Comment posted by Tanner on Wednesday, February 4, 2009 9:42 AM
another useful article! Thanks so much for writing it.

I can't wait to see the custom paging UI stuff so I don't pull back every row on my query each time I change pages.
Comment posted by RM on Thursday, February 5, 2009 12:21 AM
Very useful  article.Thank u so much for ur effort.
Comment posted by Thanigainathan on Thursday, February 5, 2009 12:22 AM
Hi,

This article is really nice. Thanks for the letting us know this features.

But where the dropdown based paging will be useful ? like some practical scenarios where it will be useful.

Thanks,
Thani
Comment posted by Danny on Tuesday, February 17, 2009 10:17 AM
Thanks for the article, but how to change page without a PostBack? I have the problem with the DDL, because it repopulates at each PostBack, so my SelectedIndexChanged is never fired.
Comment posted by kirthika on Sunday, February 22, 2009 3:49 AM
ur article is very helpful to me.
Comment posted by Majith on Friday, March 6, 2009 4:22 AM
Simply superb
Comment posted by Ram Babu on Wednesday, March 25, 2009 6:50 AM
Great Article
Comment posted by Denise on Friday, April 10, 2009 11:38 AM
Extremly Helpful...exactly what I needed
Thanks,
DS
Comment posted by yogi on Tuesday, April 14, 2009 7:03 AM
ddlPaging_SelectedIndexChanged event is not getting fired
Comment posted by MD on Tuesday, July 14, 2009 12:43 PM
Accomplished the task - good article.
Comment posted by User on Wednesday, September 2, 2009 5:38 AM
Thanks for Tip 3!
Comment posted by Akhil on Friday, September 11, 2009 2:48 AM
Really nice one.. It helps to understand more about paging
Comment posted by Andrei on Tuesday, March 22, 2011 4:11 AM
Fantastic, thanks.
Comment posted by wqerwrwer on Friday, June 24, 2011 6:04 AM
good one
Comment posted by dsdsdfddfdfdfdf on Wednesday, August 10, 2011 8:21 AM
fdfdfdfdfdfdf
Comment posted by Kumar on Monday, August 22, 2011 1:23 AM
Thanks for the tips :) Very useful.
Comment posted by Shamjith on Tuesday, March 6, 2012 3:28 AM
Very useful
Comment posted by Armend on Wednesday, May 16, 2012 3:41 PM
Very helpfull thanks a lot and pls keep posting
Comment posted by Nilanjana Paul on Thursday, January 24, 2013 7:39 AM
This article is really very very helpful. Thank you so much.
I was facing a problem to show the selected pageand I don't know how to overcome. But this article solve my problem.
Please keep posting.
Comment posted by debugger on Thursday, January 31, 2013 3:31 AM
Does not work. Dropdownlist is sometimes empty, sometimes shows first page when I click 2 from the dropdownlist.
Comment posted by Sateesh on Thursday, October 17, 2013 1:29 AM
Tip 4 displaying pager inspite no excess records in the datasource isnt working .. for cannot find the pager control..

Could you please help me on this..
Comment posted by Sateesh on Thursday, October 17, 2013 1:32 AM
sorry earlier comment was for Tip3 bymistake put it as tip4 ...
Comment posted by Mike on Friday, April 18, 2014 7:53 AM
Wow great article dude I love it!
Comment posted by amendra on Wednesday, July 16, 2014 2:15 AM
can you please help me out i want to use the paging in my page but i want when i click on second button the data of first button should also display with second.... is it possible

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel