Custom Paging With GridView in ASP.NET 4.5

This article will demonstrate, the new feature of GridView Control in ASP.NET 4.5.

In my previous article I discussed how to upload Multiple file using FileUpload server control in ASP.NET 4.5.

Now, in this article I will show another new feature of ASP.NET 4.5, the GridView Server control.

When there are bulk records to show in the GridView, developers often use paging to distribute the complete records with multiple pages to show the records in the GridView. This means that, when you change the page index, the GridView is bound everytime  from the database to show the next records.

There are mainly two ways to implement paging in the GridView.

The first is, we can use Gridview's default paging by setting it's property AllowPaging="true". The GridView will show the pager itself depending on the PageSize and total records. But this way is very tedious and degrades the performance of the application because everytime the PageIndex changes, the GridView will be bound with the complete datasource that is not required at all, as we need to show only data  to the corresponding PageIndex.

To improve the performance of the web application we usually create a custom paging control using many buttons or in any other way, since it binds the GridView with only relevant rows when the PageIndex changes. But it was also very tedious to handle all the combinations of clicks on page links and write a lot of code-behind code in the .cs file.

But, inASP.NET 4.5, the enhanced version of GridView resolved the preceding issues related to paging that I described earlier. Now, we can implement paging using the combination of Gridview's built-in paging with custom paging logic. In order to do this, the two new properties of the GridView is provided in ASP.NET 4.5.

Let's learn about both of these.

VirtualItemCount: This is the new attribute that must be used to implement this feature. This property gives the total records count that are available in your datasource. Based on this property GridView decided the number of pages to be shown in the pager control. Regarding this property two points are to be remembered:

1. You have more records count than the value of PageSize you will set.

2. The value of VirtualItemCount's must be higher than the PageSize value, otherwise the pager control will not be shown in the GridView.

3 If you set this property in code-behind, then it must be set before the DataBind method.

You can either set the value of this property equal to the total number of records in the database or you can also set some reasonable count number when the database is very large that satisfies the preceding two conditions.

AllowCustomPaging: This is another property you must use. This attribute tells the GridView that we are going to use CustomPaging with the control and helps us to implement built in paging with custom paging logic.

This attribute takes the Boolean value either true or false. You must set the value true to implement the built-in custom paging with GridView.

After implement the preceding properties, now you must handle one more event at the end. You will need to work with the PageIndexChanging event of GridView. In this event you need to write some lines of code.

1. First, get the new page index with NewPageIndex property of e and set it to the GridView PageIndex property.

2. And, then fetches the records on the basis of PageSize and the current PageIndex values from the database for that specific page number.

Now, if you have 50 records in the database and your PageSize is 10, then the GridView is bound with only 10 records to corresponding PageIndex. Now using the custom paging logic the GridView is loaded with only the data you needed.

After getting the conceptual knowledge, let's start coding to use GridView paging with custom paging logic in ASP.NET 4.5.

Open an ASP.NET application in the Visual Studio 2012.

Code of ASPX page.

The following mark to set GridView control.

custom-paging-in-gridview.jpg

As you can see in the code above, I used the "AllowPaging" and "AllowCustomPaging" properties of the GridView control.

  • Setting these two properties is not enough for us. This will not take effect on the GridView custom paging. You need to do some more code.

Now to do the code-behind coding.

Code Behind:

Set the "VirtualItemCount" property of the GridView with the total number of records in the database. And bind the datasource with PageSize 10 and PageIndex value

0 as this is first page to show.

protected void Page_Load(object sender, EventArgs e)

{

   if (!IsPostBack)

   {

      CustomPaging_GridView.VirtualItemCount = GetTotalCount();

      GetPageData(0, 10);

   }

}

After that we need to write code in the PageIndexChanging event of the GridView and bind the grid with the current page.

protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

        CustomPaging_GridView.PageIndex = e.NewPageIndex;

        GetPageData(e.NewPageIndex, 10);

}

Here, I also create two Stored Procedures in SQL Server; one to fetch the total records count and another to fetch the data corresponding to the current page index.

To get the total records count:

create procedure gettotalcount

as

begin

select COUNT(*) from HumanResources.Employee

end        

Stored Procedure for implementing the custom paging logic:

create procedure GetRecords

(

@PageIndex int,

@PageSize int

)

as

begin

select

      [NationalIDNumber],

      [LoginID],    

      [JobTitle],

      [BirthDate],

      [MaritalStatus],

      [Gender]

from HumanResources.Employee

where businessentityid
between ((@PageIndex*10)+1) and ((@PageIndex+1)*@PageSize)

end

 

Here is the entire code of the application.

ASPX markup code.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomPaging.aspx.cs" Inherits="CustomPaging" %>

 

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">       

        <div>

             <asp:GridView ID="CustomPaging_GridView" AutoGenerateColumns="true" runat="server" PageSize="10"

                AllowPaging="true" AllowCustomPaging="true" OnPageIndexChanging="GridView_PageIndexChanging">            
                <PagerSettings Mode="NextPreviousFirstLast" FirstPageText="First" LastPageText="Last" NextPageText="Next" PreviousPageText="Previous" />
            
</asp:GridView>
        </div>
    </form>
</
body>
</
html>
 

In the code above, I used PagerSetting mode to display the paging. You can see more modes in my previous article, click here PagerSetting Modes in ASP.NET GridView Control.

.Code for .cs file (C#).

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO;

using System.Data;

using System.Data.SqlClient;

 

public partial class CustomPaging : System.Web.UI.Page

{

    SqlDataAdapter da;

    DataTable dt;  

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            CustomPaging_GridView.VirtualItemCount = GetTotalCount();

            GetPageData(0, 10);

        }

    }

    private int GetTotalCount()

    {

        da = new SqlDataAdapter("gettotalcount", "server=.;database=AdventureWorks2008R2;user=--;pwd=--");

        dt = new DataTable();

        da.Fill(dt);

        return Convert.ToInt16(dt.Rows[0][0].ToString());

    }

    protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

        CustomPaging_GridView.PageIndex = e.NewPageIndex;

        GetPageData(e.NewPageIndex, 10);

    }

    public void GetPageData(int current, int pagesize)

    {

        da = new SqlDataAdapter("GetRecords", "server=.;database=AdventureWorks2008R2;user=--;pwd=--");

        SqlParameter p = new SqlParameter("@PageSize", pagesize);

        SqlParameter p1 = new SqlParameter("@PageIndex", current);

        da.SelectCommand.Parameters.Add(p);

        da.SelectCommand.Parameters.Add(p1);

        da.SelectCommand.CommandType = CommandType.StoredProcedure;

        dt = new DataTable();

        da.Fill(dt);

        CustomPaging_GridView.DataSource = dt;

        CustomPaging_GridView.DataBind();

    }

}

As you can see in the code above, I fetched the total records count and set it to the "VirtualItemCount" attribute of GridView at page load time and load the GridView with starting page index. After that I am fetching what I need for the current page and not binding the entire table to the GridView.

Now, build the application and run it.

You will see that the Gridvew is populated with only 10 records for the first page.

Gridview-paging-inasp.net4.5.jpg

Now, it will fetch the records easily when the page index is changed with only the required data that is needed without loading the complete table everytime.