Click here to Skip to main content
11,923,958 members (66,899 online)
Click here to Skip to main content
Add your own
alternative version


36 bookmarked

Custom paging with ASP.NET GridView

, 26 Jun 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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;



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)


About the Author

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

You may also be interested in...

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
tanweer akhtar21-Mar-13 19:17
membertanweer akhtar21-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
tanweer akhtar15-Mar-13 19:39
membertanweer akhtar15-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
tanweer akhtar14-Mar-13 19:55
membertanweer akhtar14-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
sam2222216-Feb-13 21:25
membersam2222216-Feb-13 21:25 
GeneralRe: User Control (Ascx) Pin
tanweer akhtar17-Feb-13 18:21
membertanweer akhtar17-Feb-13 18:21 
GeneralMy vote of 5 Pin
sam2222216-Feb-13 21:21
membersam2222216-Feb-13 21:21 
GeneralMy vote of 5 Pin
sam2222215-Feb-13 11:59
membersam2222215-Feb-13 11:59 
GeneralRe: My vote of 5 Pin
tanweer akhtar17-Feb-13 18:19
membertanweer akhtar17-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
tanweer akhtar16-Jan-13 6:12
membertanweer akhtar16-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
tanweer akhtar13-Jan-13 20:47
membertanweer akhtar13-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
tanweer akhtar27-Nov-12 18:15
membertanweer akhtar27-Nov-12 18:15 
QuestionThanks Brother Pin
inder198417-Nov-12 8:00
memberinder198417-Nov-12 8:00 
GeneralMy vote of 3 Pin
Pravin05-Nov-12 0:19
memberPravin05-Nov-12 0:19 
GeneralMy vote of 3 Pin
Pravin05-Nov-12 0:13
memberPravin05-Nov-12 0:13 
GeneralMy vote of 5 Pin
Member 817856117-Oct-12 3:51
memberMember 817856117-Oct-12 3:51 
GeneralRe: My vote of 5 Pin
tanweer akhtar31-Oct-12 21:39
membertanweer akhtar31-Oct-12 21:39 
GeneralRe: My vote of 5 Pin
tanweer akhtar31-Oct-12 21:41
membertanweer akhtar31-Oct-12 21:41 
QuestionWill it work after sorting ? Pin
palakshamb4-Oct-12 22:33
memberpalakshamb4-Oct-12 22:33 
AnswerRe: Will it work after sorting ? Pin
tanweer akhtar4-Oct-12 23:00
membertanweer akhtar4-Oct-12 23:00 
GeneralReally Awsome!! Pin
Member 274363726-Jul-12 0:25
memberMember 274363726-Jul-12 0:25 
GeneralMy vote of 2 Pin
giri444417-Jul-12 22:44
membergiri444417-Jul-12 22:44 
GeneralMy vote of 5 Pin
Farhan Ghumra8-Jul-12 20:23
memberFarhan Ghumra8-Jul-12 20:23 
GeneralRe: My vote of 5 Pin
tanweer akhtar29-Jul-12 19:17
membertanweer akhtar29-Jul-12 19:17 
Questionpostback Pin
Member 79963862-Jul-12 11:54
memberMember 79963862-Jul-12 11:54 
have you tried to create pager buttons and their postback methods after user clicked one of the pager buttons? any idea how to register their click handler again on its own postback method?
AnswerRe: postback Pin
tanweer akhtar2-Jul-12 19:48
membertanweer akhtar2-Jul-12 19:48 
GeneralRe: postback Pin
Member 79963863-Jul-12 7:24
memberMember 79963863-Jul-12 7:24 
GeneralRe: postback Pin
tanweer akhtar4-Jul-12 19:43
membertanweer akhtar4-Jul-12 19:43 
GeneralMy vote of 5 Pin
salahuddinuk2-Jul-12 8:13
membersalahuddinuk2-Jul-12 8:13 
GeneralRe: My vote of 5 Pin
tanweer akhtar2-Jul-12 19:35
membertanweer akhtar2-Jul-12 19:35 
GeneralVery Very Good Pin
Anoop Ananthan28-Jun-12 5:55
memberAnoop Ananthan28-Jun-12 5:55 
GeneralRe: Very Very Good Pin
tanweer akhtar28-Jun-12 19:26
membertanweer akhtar28-Jun-12 19:26 
GeneralMy vote of 1 Pin
kuldeep158627-Jun-12 3:45
memberkuldeep158627-Jun-12 3:45 
GeneralRe: My vote of 1 Pin
tanweer akhtar27-Jun-12 19:52
membertanweer akhtar27-Jun-12 19:52 
GeneralRe: My vote of 1 Pin
kuldeep158628-Jun-12 3:58
memberkuldeep158628-Jun-12 3:58 
GeneralMy vote of 4 Pin
Muhammad Hussain Tabassum26-Jun-12 22:16
memberMuhammad Hussain Tabassum26-Jun-12 22:16 
GeneralRe: My vote of 4 Pin
tanweer akhtar26-Jun-12 22:20
membertanweer akhtar26-Jun-12 22:20 
Questioncustom paging in datagridview Pin
ehsan assu26-Jun-12 21:41
memberehsan assu26-Jun-12 21:41 
QuestionWhy so serious? Pin
Vitaly Tomilov26-Jun-12 5:33
memberVitaly Tomilov26-Jun-12 5:33 
AnswerRe: Why so serious? Pin
tanweer akhtar26-Jun-12 19:34
membertanweer akhtar26-Jun-12 19:34 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.151125.3 | Last Updated 26 Jun 2012
Article Copyright 2012 by tanweer
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid