Click here to Skip to main content
15,498,966 members
Articles / Web Development / ASP.NET
Posted 26 Jun 2012


37 bookmarked

Custom paging with ASP.NET GridView

Rate me:
Please Sign up or sign in to vote.
4.69/5 (29 votes)
26 Jun 2012CPOL2 min read
Easy way to implement ASP.NET GridView paging .


A scalable web application uses paging techniques to load large data. Paging enables a web-application to efficiently retrieve only the specific rows it needs from the database, and avoid having to pull back dozens, hundreds, or even thousands of results to the web-server. Today I am going to demonstrate how a custom paging can be implemented in application. It is a very essential approach to use paging technique in applications where lot of data to be loaded from database. Using a good paging technique can lead to significant performance wins within your application (both in terms of latency and throughput), and reduce the load on your database. 


GridView has built-in support for paging but it is very heavy and costly when it comes to deal large amount of data. The idea to develop a custom paging comes from stackoverflow website where lot of data are being divided into many page using custom paging technique very smoothly. 

Using the code

First of all the big magic here is the SQL Query which makes it easy to handle the amount of data to be fetch from database.  I used the NorthWind database's  Orders table which has over 800 records. Here Index and Size are two integer variables which are comes from querystring.

  • Index is the current page number
  • Size is the no of records to be shown on a page
select * from (SELECT  ROW_NUMBER() OVER (ORDER BY CustomerID asc) as row,* FROM Orders) 
  tblTemp WHERE row between (" + index + " - 1) * " + size + 
  " + 1 and " + index + "*" + size + " ";
            SQL += " select COUNT(*) from Orders 

First time when the page loads it has no querystring values so the default Index is 1 and Size is 10. You can latter change the page size, there are options for 10 records per page and 15 records per page. I tried to explain all necessary points within the code. 

void BindGrid(int size, int index)
    //page url--get from Web.config file--------change it as your page URL
    string url = ConfigurationManager.AppSettings["URL"].ToString();
    //string templates for links
    string link = "<a  href='" + url + 
      "?Index=##Index##&amp;Size=##Size##'><span class='page-numbers'>##Text##</span></a>";
    string link_pre = "<a href='" + url + 
      "?Index=##Index##&amp;Size=##Size##'><span class='page-numbers prev'>##Text##</span></a>";
    string link_next = "<a href='" + url + 
      "?Index=##Index##&amp;Size=##Size##'><span class='page-numbers next'>##Text##</span></a>";
        //the connectionstring from Web.config file--------change it as per your database settings
        String ConnStr = ConfigurationManager.ConnectionStrings["myConnection"].ToString();
        //the sql query with paging logics
        //here table name is "Orders" change this name as your requirement.
        //"CustomerID" is the column by which you can sort the records, change it as per your requirement
        String SQL = @"select * from (SELECT  ROW_NUMBER() OVER (ORDER BY CustomerID asc) as row,* FROM Orders) tblTemp
                    WHERE row between (" + index + " - 1) * " + size + 
                    " + 1 and " + index + "*" + size + " ";
        SQL += " select COUNT(*) from Orders";
        //fetching data from database suing SqlDataAdapter Fill method to bind the Gridview
        SqlDataAdapter ad = new SqlDataAdapter(SQL, ConnStr);
        DataSet ds = new DataSet();
        //bind the grid with the ist data table---------remember that this dataset consist of two data tables
        this.gvPaging.DataSource = ds.Tables[0];
        ////////get the n number of record///////////
        Double n = Convert.ToDouble(Convert.ToInt32(ds.Tables[1].Rows[0][0]) / size);
        /////////setting page numbers with links
        if (index != 1)
            lblpre.Text = link_pre.Replace("##Size##", size.ToString()).Replace(
              "##Index##", (index - 1).ToString()).Replace("##Text##", "prev");
            lblpre.Text = "<span class='page-numbers prev'>prev</span>";
        if (index != Convert.ToInt32(n))
            lblnext.Text = link_next.Replace("##Size##", size.ToString()).Replace(
              "##Index##", (index + 1).ToString()).Replace("##Text##", "next");
            lblnext.Text = "<span class='page-numbers next'>next</span>";
        //generate dynamic paging 
        int start;
        if (index <= 5) start = 1;
        else start = index - 4;
        for (int i = start; i < start + 7; i++)
            if (i > n) continue;
            //create dynamic HyperLinks 
            HyperLink lnk = new HyperLink();

            lnk.ID = "lnk_" + i.ToString();
            if (i == index)//current page
                lnk.CssClass = "page-numbers current";
                lnk.Text = i.ToString();
                lnk.Text = i.ToString();
                lnk.CssClass = "page-numbers";
                lnk.NavigateUrl = url + "?Index=" + i + "&Size=" + size + "";
            //add links to page
        //set up the ist page and the last page
        if (n > 7)
            if (index <= Convert.ToInt32(n / 2))
                lblLast.Visible = true;
                lblIst.Visible = false;
                lblLast.Text = link.Replace("##Index##", n.ToString()).Replace(
                  "##Size##", size.ToString()).Replace("##Text##", n.ToString());
                spDot2.Visible = true;
                spDot1.Visible = false;
                lblLast.Visible = false;
                lblIst.Visible = true;
                lblIst.Text = link.Replace("##Index##", (n - n + 1).ToString()).Replace(
                  "##Size##", size.ToString()).Replace("##Text##", (n - n + 1).ToString());
                spDot2.Visible = false;
                spDot1.Visible = true;
    catch (Exception ee)
        //catch the exception

In the above method you have to change the Config settings like the Connectionstring and page url which can be edited in the web.config file.

On the aspx page there are six labels:

  • previous page link
  • ist page link 
  • dot before ist page link 
  • next page link
  • last page link 
  • dot before ist page link

and a PlaceHolder for other page numbers 

<div class="pager fl">
    <asp:Label runat="server" ID="lblpre"></asp:Label>
    <asp:Label runat="server" ID="lblIst" Visible="false"></asp:Label>
    <asp:Label runat="server" ID="spDot1" CssClass="page-numbers prev" Visible="false"
    <asp:PlaceHolder ID="pl" runat="server"></asp:PlaceHolder>
    <asp:Label runat="server" ID="spDot2" Visible="false" CssClass="page-numbers prev"
    <asp:Label runat="server" ID="lblLast" Visible="false"></asp:Label>
    <asp:Label runat="server" ID="lblnext"></asp:Label>
<div class="pager f2">
    <a id="A1" href="javascript:void(0);" runat="server" class="page-numbers">10</a>&nbsp;
    <a href="javascript:void(0);" id="A2" runat="server" class="page-numbers">15</a><span
        class="page-numbers desc">per page</span>

HyperLinks are dynamically created and set their Links and css and add in the placeholder at page load.  

Another important point is to replace the Table name in the sql Query and the column name in the order by statement.   

To change the page size there are two options(html anchor tags) on the right side of the page. You can set 10 records per page or 15 records per page. Using JQuery I capture the click events of these two html anchors and set the currently set page size  in a HiddenField and  reload the current page by passing Index and Size in querystring.

<input type="hidden" runat="server" id="hdSize" />

jQuery Code:

<script type="text/javascript">
    $(document).ready(function () {
        $('#A1').click(function () {
        $('#A2').click(function () {
    function Loadpage() {
        try {
            //reload page using new page size
            var url = $(location).attr('href');
            var index = "Index=1";
            if (url.indexOf('Index') > 0) {
                index = url.split('?')[1];
                index = index.split('&')[0];
            url = url.split('?')[0] + "?" + index + "&Size=" + $('#hdSize').val() + "";
            window.location.href = url;
        } catch (e) {

CSS: CSS plays an important role in this paging. Although all works done but these all looks very poor untill a good css effect is given. 

    color: #55ff00;
    color: #74aacc;

    float: left;
    float: right;
    padding-right: 200px;
    margin-top: 20px;
    margin-bottom: 20px;
    font-family: 'Helvetica Neue' ,Helvetica,Arial,sans-serif;
    border: 1px solid #CCC;
    color: #808185;
    display: block;
    float: left;
    font-size: 130%;
    margin-right: 3px;
    padding: 4px 4px 3px;
    text-decoration: none;
    background-color: #808185;
    border: 1px solid #808185;
    color: white;
    font-weight: bold;
}, .page-numbers.prev
    border: 1px solid white;
    border: none;
    margin-bottom: 10px;


Image 1


It took a whole week to develop this article and ist release date is 26th June 2012 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer LIFELONG Pakistan, Islamabad
Pakistan Pakistan
Software Engineer at LIFELONG Pakistan,

Comments and Discussions

GeneralMy vote of 5 Pin
Renju Vinod2-Oct-13 21:47
professionalRenju Vinod2-Oct-13 21:47 
GeneralRe: My vote of 5 Pin
tanweer2-Oct-13 22:05
Membertanweer2-Oct-13 22:05 
Questionnavigation number not working .. what to do to fix it Pin
Nastik 20119-May-13 23:55
MemberNastik 20119-May-13 23:55 
Questiongridview last page -with range validator with maximum date in item template causes server exception error Pin
Travelthrprog25-Apr-13 5:09
MemberTravelthrprog25-Apr-13 5:09 
GeneralMy vote of 5 Pin
Savalia Manoj M21-Mar-13 3:27
MemberSavalia Manoj M21-Mar-13 3:27 
GeneralRe: My vote of 5 Pin
tanweer21-Mar-13 19:17
Membertanweer21-Mar-13 19:17 
GeneralMy vote of 5 Pin
shanawazway15-Mar-13 1:28
Membershanawazway15-Mar-13 1:28 
GeneralRe: My vote of 5 Pin
tanweer15-Mar-13 19:39
Membertanweer15-Mar-13 19:39 
QuestionHow to impliment with store procedure Pin
prince_rumeel11-Mar-13 6:38
Memberprince_rumeel11-Mar-13 6:38 
AnswerRe: How to impliment with store procedure Pin
tanweer14-Mar-13 19:55
Membertanweer14-Mar-13 19:55 
GeneralRe: How to impliment with store procedure Pin
prince_rumeel14-Mar-13 22:04
Memberprince_rumeel14-Mar-13 22:04 
GeneralUser Control (Ascx) Pin
Peaceful Salman16-Feb-13 21:25
MemberPeaceful Salman16-Feb-13 21:25 
GeneralRe: User Control (Ascx) Pin
tanweer17-Feb-13 18:21
Membertanweer17-Feb-13 18:21 
GeneralMy vote of 5 Pin
Peaceful Salman16-Feb-13 21:21
MemberPeaceful Salman16-Feb-13 21:21 
GeneralMy vote of 5 Pin
Peaceful Salman15-Feb-13 11:59
MemberPeaceful Salman15-Feb-13 11:59 
GeneralRe: My vote of 5 Pin
tanweer17-Feb-13 18:19
Membertanweer17-Feb-13 18:19 
QuestionPass Search Parameters to new index page Pin
Lijo_C_J15-Jan-13 0:17
MemberLijo_C_J15-Jan-13 0:17 
AnswerRe: Pass Search Parameters to new index page Pin
tanweer16-Jan-13 6:12
Membertanweer16-Jan-13 6:12 
GeneralMy vote of 5 Pin
klay16-Dec-12 13:46
Memberklay16-Dec-12 13:46 
GeneralRe: My vote of 5 Pin
tanweer13-Jan-13 20:47
Membertanweer13-Jan-13 20:47 
GeneralMy vote of 1 Pin
Rahul Gangahar27-Nov-12 8:16
MemberRahul Gangahar27-Nov-12 8:16 
GeneralRe: My vote of 1 Pin
tanweer27-Nov-12 18:15
Membertanweer27-Nov-12 18:15 
QuestionThanks Brother Pin
inder198417-Nov-12 8:00
Memberinder198417-Nov-12 8:00 
GeneralMy vote of 3 Pin
Pravin Harchandani5-Nov-12 0:19
professionalPravin Harchandani5-Nov-12 0:19 
GeneralMy vote of 3 Pin
Pravin Harchandani5-Nov-12 0:13
professionalPravin Harchandani5-Nov-12 0:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.