Click here to Skip to main content
15,438,920 members
Articles / Web Development / ASP.NET
Posted 3 Nov 2006


112 bookmarked

GridView Custom Paging

Rate me:
Please Sign up or sign in to vote.
4.43/5 (38 votes)
3 Nov 20062 min read
This article demonstrates how you can use custom paging to improve the performance of GridView paging.


The GridView control provides you with an easy way to display the number of items on a page without taking much space, with the help of paging. You can enable the paging feature in the GridView control in seconds. The built-in paging is pretty good if you are fetching less than 100 items. As soon as the number of items increases, the performance suffers. The main reason for the performance kill is that whenever you go to a new page of the GridView, it fetches all the items from the database. In this article, I will demonstrate how you can use custom paging to improve the performance of GridView paging.

Database and Stored Procedure

I will be using the good old Northwind database. The stored procedure is written by Greg Hamilton. You can view Greg Hamilton's article here: A More Efficient Method for Paging Through Large Result Sets. Greg created a very efficient stored procedure that works without the use of temporary tables or the TABLE variable.

I have modified the stored procedure by adding a few fields. Here is the modified version of the stored procedure:

CREATE PROCEDURE [usp_GetProducts] 
@startRowIndex int,
@maximumRows int, 
@totalRows int OUTPUT


DECLARE @first_id int, @startRow int

SET @startRowIndex =  (@startRowIndex - 1)  * @maximumRows

IF @startRowIndex = 0 
SET @startRowIndex = 1

SET ROWCOUNT @startRowIndex

SELECT @first_id = ProductID FROM Products ORDER BY ProductID

PRINT @first_id

SET ROWCOUNT @maximumRows

SELECT ProductID, ProductName FROM Products WHERE 
ProductID >= @first_id 

-- GEt the total rows 

SELECT @totalRows = COUNT(ProductID) FROM Products

I highly recommend that you check out Greg’s article in which he explains in detail how the stored procedure works.

Displaying Paged Data on the Page

I will be paging through the records using the “Next” and the “Previous” buttons. The Label control will display our current location in the paged GridView. Let’s first set up some of the variables.

protected int currentPageNumber = 1;
private const int PAGE_SIZE = 10;

The currentPageNumber represents the current page of the GridView, and the PAGE_SIZE is the total number of records displayed on each page. You can also allow the user to adjust the page size using a DropDownList, but that is not covered in this article.

Next, we need to bind the data source to the GridView. Let’s check out the BindData method as a whole, and later I will dissect it so you will have a better idea.

private void BindData()
    string connectionString = "Server=localhost;" + 
    SqlConnection myConnection = new SqlConnection(connectionString);
    SqlCommand myCommand = new SqlCommand("usp_GetProducts", 
    myCommand.CommandType = CommandType.StoredProcedure;

    myCommand.Parameters.AddWithValue("@maximumRows", PAGE_SIZE);
    myCommand.Parameters.Add("@totalRows", SqlDbType.Int, 4);
    myCommand.Parameters["@totalRows"].Direction = 

    SqlDataAdapter ad = new SqlDataAdapter(myCommand);

    DataSet ds = new DataSet();

    gvProducts.DataSource = ds;

    // get the total rows 
    double totalRows = (int)myCommand.Parameters["@totalRows"].Value;

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

    lblCurrentPage.Text = currentPageNumber.ToString(); 

    if (currentPageNumber == 1)
        Btn_Previous.Enabled = false;

        if (Int32.Parse(lblTotalPages.Text) > 0)
            Btn_Next.Enabled = true;
            Btn_Next.Enabled = false;


        Btn_Previous.Enabled = true;

        if (currentPageNumber == Int32.Parse(lblTotalPages.Text))
            Btn_Next.Enabled = false;
        else Btn_Next.Enabled = true; 

Now, let’s take a look at the above code in more detail. I am sending the currentPageNumber and the PAGE_SIZE into the database so I can get the data for the current page. The totalRows variable returns the total number of rows in the table. Once I have totalRows, I calculate the total number of pages that will be used for this GridView. The total number of pages is calculated by using a small helper function:

private int CalculateTotalPages(double totalRows)
    int totalPages = (int)  Math.Ceiling(totalRows / PAGE_SIZE);

    return totalPages; 

At the end of the BindData method, there are some conditional checks which ensure that the Next and Previous buttons are only displayed when applicable.

Attaching the Events to the Buttons

The final thing that is left is to attach the events to the Button controls. Check out the following code in which I created two Button controls.

<asp:Button ID="Btn_Previous" CommandName="Previous" 
            runat="server" OnCommand="ChangePage" 
            Text="Previous" />
<asp:Button ID="Btn_Next" runat="server" CommandName="Next" 
            OnCommand="ChangePage" Text="Next" />

Both the buttons call the ChangePage event which is shown below:

// This method will handle the navigation/ paging index
protected void ChangePage(object sender, CommandEventArgs e)
    switch (e.CommandName)
        case "Previous":
            currentPageNumber = Int32.Parse(lblCurrentPage.Text) - 1;

        case "Next":
            currentPageNumber = Int32.Parse(lblCurrentPage.Text) + 1; 


The ChangePage event is used to change the page number of the GridView and also to update the Label text by calling the BindData method.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Written By
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.

I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

QuestionComment Pin
Member 97893603-Dec-13 5:30
MemberMember 97893603-Dec-13 5:30 
QuestionCustom paging in using stored procedure in gridview Pin
Vivek.netprofessional16-Sep-13 7:48
MemberVivek.netprofessional16-Sep-13 7:48 
GeneralMy vote of 5 Pin
Razi Syed30-May-12 8:54
MemberRazi Syed30-May-12 8:54 
GeneralMy vote of 4 Pin
Muhammad Umar Lahore13-May-12 23:38
MemberMuhammad Umar Lahore13-May-12 23:38 
QuestionClicking next not displaying next set of records Pin
harsha.cs29-Mar-12 22:10
Memberharsha.cs29-Mar-12 22:10 
Questionnice Pin
Member 856458916-Mar-12 2:09
MemberMember 856458916-Mar-12 2:09 
Generalthis blog is very useful for me but i want share small change Pin
smp@1232-Apr-11 23:55
Membersmp@1232-Apr-11 23:55 
GeneralNot able to display Gridview Pin
shantesh.n.kulkarni20-Dec-10 0:56
Membershantesh.n.kulkarni20-Dec-10 0:56 
QuestionHow to implement custom sorting on top of custom paging Pin
Member 116262914-May-10 4:07
MemberMember 116262914-May-10 4:07 
GeneralPlease add this is also for custom paging..... [modified] Pin
gsvasu255-Mar-10 23:27
Membergsvasu255-Mar-10 23:27 
GeneralMy vote of 1 Pin
gsvasu255-Mar-10 23:23
Membergsvasu255-Mar-10 23:23 
GeneralStoredProcedure have some error Pin
Member 470203518-Feb-10 23:56
MemberMember 470203518-Feb-10 23:56 
GeneralSome suggestions Pin
Mario Majčica1-Jul-09 22:21
professionalMario Majčica1-Jul-09 22:21 
Generalgridview custom paging Pin
Bob MacNeel22-Jan-09 4:41
MemberBob MacNeel22-Jan-09 4:41 
QuestionSqlDataAdapter Pin
dffefqefe4-Jan-07 16:57
Memberdffefqefe4-Jan-07 16:57 
AnswerRe: SqlDataAdapter Pin
ryanoc3338-May-08 5:05
Memberryanoc3338-May-08 5:05 
GeneralUsing Labels Pin
fahiemulleh21-Dec-06 22:45
Memberfahiemulleh21-Dec-06 22:45 
Generalpage number issue Pin
mbowles2015-Dec-06 9:18
Membermbowles2015-Dec-06 9:18 
GeneralRe: page number issue Pin
donnapep11-Dec-06 6:57
Memberdonnapep11-Dec-06 6:57 
GeneralRe: page number issue Pin
Noham PETIT25-Dec-07 17:48
MemberNoham PETIT25-Dec-07 17:48 

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.