Custom Paging With GridView 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 every time 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 every time 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.


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.

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.    if (!IsPostBack)  
  4.    {  
  5.       CustomPaging_GridView.VirtualItemCount = GetTotalCount();  
  6.       GetPageData(0, 10);  
  7.    }  
  8. } 

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

  1. protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)  
  2. {  
  3.     CustomPaging_GridView.PageIndex = e.NewPageIndex;  
  4.     GetPageData(e.NewPageIndex, 10);  
  5. } 

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:

  1. create procedure gettotalcount  
  2. as  
  3. begin  
  4. select COUNT(*) from HumanResources.Employee  
  5. end 

Stored Procedure for implementing the custom paging logic:

  1. create procedure GetRecords  
  2. (  
  3. @PageIndex int,  
  4. @PageSize int  
  5. )  
  6. as  
  7. begin  
  8. select  
  9.       [NationalIDNumber],  
  10.       [LoginID],  
  11.       [JobTitle],  
  12.       [BirthDate],  
  13.       [MaritalStatus],  
  14.       [Gender]  
  15. from HumanResources.Employee  
  16. where businessentityid  
  17. between ((@PageIndex*10)+1) and ((@PageIndex+1)*@PageSize)  
  18. end 

Here is the entire code of the application.

ASPX markup code.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomPaging.aspx.cs" Inherits="CustomPaging" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="">  
  4. <head runat="server">  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.         <div>  
  10.              <asp:GridView ID="CustomPaging_GridView" AutoGenerateColumns="true" runat="server" PageSize="10"  
  11.                 AllowPaging="true" AllowCustomPaging="true" OnPageIndexChanging="GridView_PageIndexChanging">              
  12.                 <PagerSettings Mode="NextPreviousFirstLast" FirstPageText="First" LastPageText="Last" NextPageText="Next" PreviousPageText="Previous" />  
  13.              </asp:GridView>  
  14.         </div>  
  15.     </form>  
  16. </body>  
  17. </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#).

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.IO;  
  8. using System.Data;  
  9. using System.Data.SqlClient;  
  10. public partial class CustomPaging : System.Web.UI.Page  
  11. {  
  12.     SqlDataAdapter da;  
  13.     DataTable dt;    
  14.     protected void Page_Load(object sender, EventArgs e)  
  15.     {  
  16.         if (!IsPostBack)  
  17.         {  
  18.             CustomPaging_GridView.VirtualItemCount = GetTotalCount();  
  19.             GetPageData(0, 10);  
  20.         }  
  21.     }  
  22.     private int GetTotalCount()  
  23.     {  
  24.         da = new SqlDataAdapter("gettotalcount""server=.;database=AdventureWorks2008R2;user=--;pwd=--");  
  25.         dt = new DataTable();  
  26.         da.Fill(dt);  
  27.         return Convert.ToInt16(dt.Rows[0][0].ToString());  
  28.     }  
  29.     protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)  
  30.     {  
  31.         CustomPaging_GridView.PageIndex = e.NewPageIndex;  
  32.         GetPageData(e.NewPageIndex, 10);  
  33.     }  
  34.     public void GetPageData(int current, int pagesize)  
  35.     {  
  36.         da = new SqlDataAdapter("GetRecords""server=.;database=AdventureWorks2008R2;user=--;pwd=--");  
  37.         SqlParameter p = new SqlParameter("@PageSize", pagesize);  
  38.         SqlParameter p1 = new SqlParameter("@PageIndex", current);  
  39.         da.SelectCommand.Parameters.Add(p);  
  40.         da.SelectCommand.Parameters.Add(p1);  
  41.         da.SelectCommand.CommandType = CommandType.StoredProcedure;  
  42.         dt = new DataTable();  
  43.         da.Fill(dt);  
  44.         CustomPaging_GridView.DataSource = dt;  
  45.         CustomPaging_GridView.DataBind();  
  46.     }  
  47. } 

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.


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.

Similar Articles