When there are a lot of records to be displayed, then Paging is used in order to segregate the content and display it in GridView.
There are two types of paging functionalities used in ASP.net. Simple paging and Custom Paging.
Simple Paging is the default paging setting in GridView, which will display the records depending on the page size and the number of records.This method of paging is not desired as it would bring down the performance of the application.
This tutorial will discuss in detail the various steps and procedures involved in Custom paging and why is it preferred over simple paging.
2. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
2
WHAT IS PAGING ?
When there are lacs or thousands of records to show in the GridView, we often use paging to divide the
complete records with multiple pages to show the records in the GridView. This tutorial provides an overview
on Customer Paging – a new feature in ASP.NET 4.5.
Generally, we have the following two ways to bind GridView with paging functionality.
1. Simple Paging - In simple paging we can use GridView’s default paging by setting its property
AllowPaging=”true”. The GridView will show the paging itself depending on the PageSize and total records.
But Simple Paging brings down the performance of the application because every time the PageIndex
changes, the GridView will be bind with the complete datasource. This is not required at all, as we need to
show only data to the respective PageIndex.
2. Custom Paging - To improve the performance of the web application we usually create a custom
paging control using many buttons, repeater or in any other way, since it binds the GridView with only the
respective rows when the PageIndex changes. But it is also very typical to handle all the combinations of
clicks on page links and write a lot of code in code behind.
Now, in ASP.NET 4.5, this feature of GridView resolved the previous issues related to paging. Now, we can
implement paging using the combination of GridView’s built-in paging with custom paging logic.
To implement this feature there are two new properties of GridView are as:
1. VirtualItemCount - This property returns the total records count that are available in our datasource. On
behalf of this property GridView auto implements the no. of pages with respect to the page size of GridView.
Before using this property we should keep in mind the following two things -
• There will be greater than or equal to number of records inside datasource as we are going to set
pagesize of GridView
• VirtualItemCount’s value should be higher otherwise we cannot view paging inside GridView
Note - If we want to set this property dynamically in code behind then we should set this property before
GridView databind.
2. AllowCustomPaging - This property sets the custom paging of GridView. It takes the Boolean value either
true or false. Now, for example if datasource has 10000 records and page size is 20. Then GridView will bind
with only 20 records with respect to the PageIndex. So GridView will bind only with required data. It will not
bind 10000 records.
3. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
3
This is step by step tutorial to implement custom paging inside GridView with an example as:
Step 1
Set AllowCustomPaging=”true” to implement inside GridView in .aspx page
Step 2
Add PagerSetting inside GridView as given below:
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”CutomPagingGridView.aspx.cs”
Inherits=”CutomPagingGridView” %>
<!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=”GridView1” runat=”server” AutoGenerateColumns=”true” AllowPaging=”true”
AllowCustomPaging=”true” PageSize=”10” OnPageIndexChanging=”GridView1_PageIndexChanging”>
<PagerSettings Mode=”NextPreviousFirstLast” FirstPageText=”First” LastPageText=”Last”
NextPageText=”Next” PreviousPageText=”Previous” />
</asp:GridView>
</div>
</form>
</body>
</html>
Step 3
Set virtual count i.e. total count of records from datasource in code behind .aspx.cs page.
4. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
4
Step 4
We used GetTotalCountOfData() function in codebehind to get total no of records from datasource in
code behind.
Step 5
Call BindGridData(0,10) by passing PageIndex and page size respectively to bind GridView on pageload
event.Here 0 is current PageIndex and 10 is page size.
This is PageIndex Changing event of GridView. When PageIndex will change, it binds the grid with its
respective PageIndex.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.VirtualItemCount = GetTotalCountOfData();//GetTotalCountOfData is a function to return
total count of records.
BindGridData(0, 10);//here 0 is PageIndex and page size is 10 and Bind grid data is custom function to
bind GridView
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;//Current PageIndex.
BindGridData(e.NewPageIndex, 10);
//passes current PageIndex and page size to bind grid.
}
5. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
5
2. This procedure returns the records with respect to PageIndex and page size:
create procedure getcount
as
begin
select COUNT(*) as [count] from UsersData where IsActive=1 //Users data is a data table
end
create procedure GetUserData
(
@PageIndex int,
@PageSize int
)
as
begin
select
[UserID],
[UserName],
[UserType],
[ContactNo],
[EmailID],
[Gender]
from UsersData
where IsActive=1
between ((@PageIndex*10)+1) and ((@PageIndex+1)*@PageSize)
end
Here we had created StoreProcedures inside database to fetch data and bind GridView as:
1. This procedure returns total count of records which are existing in a table:-
Create class database helper to execute store Procedure named as clsDatabaseHelper and write this
function as -
This function is used to execute the procedures which have parameters and its value.
6. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
6
public StoredProc ExecStoredProc(string sProcName, string[] sParamName, string[] sParamValue, string
ReturnType)
{
string mstr_ConnectionString;
SqlConnection mobj_SqlConnection;
SqlCommand mobj_SqlCommand;
SqlCommand cmd = null;
SqlDataAdapter da = null;
StoredProc sp = null;
StoredProc objSP = null;
DataTable DT = null;
mstr_ConnectionString
=ConfigurationManager.ConnectionStrings[“ConnectionStringDB”].ToString();
mobj_SqlConnection = new SqlConnection(mstr_ConnectionString);
mobj_SqlCommand = new SqlCommand();
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.Connection = mobj_SqlConnection;
using (mobj_SqlConnection)
{
try
{
if (mobj_SqlConnection.State == ConnectionState.Closed)
{
mobj_SqlConnection.Open();
}
sp = new StoredProc();
objSP = new StoredProc();
cmd = new SqlCommand(sProcName, mobj_SqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 30000;
7. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
7
da = new SqlDataAdapter(sProcName, mobj_SqlConnection);
da.SelectCommand = cmd;
int i;
ReturnType = ReturnType.ToUpper();
for (i = 0; i < sParamName.Length; i++)
{
cmd.Parameters.AddWithValue(sParamName[i].ToString(), sParamValue[i].ToString());
}
if (ReturnType.Contains(“DATAREADER”))
{
sp.DataReaderObject = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
else if (ReturnType.Contains(“DATATABLE”))
{
da.Fill(sp.DataTableObject);
sp.DataTableObject = sp.DataTableObject;
}
else if (ReturnType.Contains(“DATASET”))
{
da.Fill(sp.DataSetObject);
for (int j = 0; j < sp.DataSetObject.Tables.Count; j++)
{
DT = new DataTable();
DT = sp.DataSetObject.Tables[j].Copy();
DT = DT;
objSP.DataSetObject.Tables.Add(DT);
}
sp = objSP;
}
else if (ReturnType.Contains(“SINGLERECORD”))
{
8. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
88
//OpenConnection();
sp.StringObject = cmd.ExecuteNonQuery().ToString();
//CloseConnection();
}
//Clean Up Command Object
if (cmd != null)
{
cmd.Dispose();
}
//Clean Up DataAdapter Object
if (da != null)
{
da.Dispose();
}
return sp;
}
catch
{
//myTransaction.Rollback();
throw;
}
finally
{
if (sp != null) sp = null;
if (objSP != null) objSP = null;
if (DT != null) DT = null;
if (mobj_SqlConnection.State == ConnectionState.Open)
{
mobj_SqlConnection.Close();
}
}
}
}
9. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
9
public StoredProc ExecStoredProc(string sProcName, string ReturnType)
{
string mstr_ConnectionString;
SqlConnection mobj_SqlConnection;
SqlCommand mobj_SqlCommand;
SqlCommand cmd = null;
SqlDataAdapter da = null;
StoredProc sp = null;
StoredProc objSP = null;
DataTable DT = null;
mstr_ConnectionString =getDecrypt(ConfigurationManager.ConnectionStrings[“ConnectionStringDB”].
ToString());
mobj_SqlConnection = new SqlConnection(mstr_ConnectionString);
mobj_SqlCommand = new SqlCommand();
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.Connection = mobj_SqlConnection;
using (mobj_SqlConnection)
{
try
{
if (mobj_SqlConnection.State == ConnectionState.Closed)
{
mobj_SqlConnection.Open();
}
sp = new StoredProc();
objSP = new StoredProc();
cmd = new SqlCommand(sProcName, mobj_SqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 30000;
da = new SqlDataAdapter(sProcName, mobj_SqlConnection);
da.SelectCommand = cmd;
ReturnType = ReturnType.ToUpper();
This function is used to execute the procedures which do not have parameters and its value.
10. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
10
if (ReturnType.Contains(“DATAREADER”))
{
sp.DataReaderObject =
cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
else if (ReturnType.Contains(“DATATABLE”))
{
da.Fill(sp.DataTableObject);
sp.DataTableObject = sp.DataTableObject;
}
else if (ReturnType.Contains(“DATASET”))
{
da.Fill(sp.DataSetObject);
for (int j = 0; j < sp.DataSetObject.Tables.Count; j++)
{
DT = new DataTable();
DT = sp.DataSetObject.Tables[j].Copy();
objSP.DataSetObject.Tables.Add(DT);
}
sp = objSP;
}
else if (ReturnType.Contains(“SINGLERECORD”))
{
sp.StringObject = cmd.ExecuteNonQuery().ToString();
}
//Clean Up Command Object
if (cmd != null)
{
cmd.Dispose();
}
//Clean Up DataAdapter Object
if (da != null)
11. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
11
da.Dispose();
}
return sp;
}
catch
{
throw;
}
finally
{
if (sp != null) sp = null;
if (objSP != null) objSP = null;
if (DT != null) DT = null;
if (mobj_SqlConnection.State == ConnectionState.Open)
{
mobj_SqlConnection.Close();
}
}
}
}
public DataTable getcount()
{
DataTable dtCount = new DataTable();
dtDetail = null;
StoredProc objSP = new StoredProc();
clsDatabaseHelper objDB = new clsDatabaseHelper ();
try
{
objSP = objDB.ExecStoredProc(“getcount”, “DATATABLE”);
Create another class for Business logic named as clsUsers for user data and create function:
This function returns records count -
12. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
12
dtDetail = objSP.DataTableObject;
}
catch (Exception e)
{
}
return dtCount;
}
public DataTable GetUserDetail(int PageIndex, int PageSize)
{
DataTable dtDetail = new DataTable();
dtDetail = null;
string[] ParamName = new string[2];
string[] ParamValue = new string[2];
StoredProc objSP = new StoredProc();
clsDatabaseHelper objDB = new clsDatabaseHelper ();
try
{
ParamName[0] = “@PageIndex”;
ParamName[1] = “@PageSize”;
ParamValue[0] = PageIndex.ToString();
ParamValue[1] = PageSize.ToString();
objSP = objDB.ExecStoredProc(“GetUserData”, ParamName, ParamValue, “DATATABLE”);
dtDetail = objSP.DataTableObject;
}
catch (Exception e)
{
}
return dtDetail;
}
13. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
13
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CutomPagingGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.VirtualItemCount = GetTotalCount();//GetTotalCountOfData is a function to return total
count of records.
BindGridData(0, 20);//here 0 is PageIndex and page size is 20 and Bind grid data is custom function to
bind GridView
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridData(e.NewPageIndex, 10);
}
public void BindGridData(int PageIndex,int PageSize)
{
DataTable dtgrid = new DataTable();
dtgrid = null;
clsUsers objclass = new clsUsers();
dtgrid = objclass.GetUserDetail(PageIndex,PageSize);
if (dtgrid != null && dtgrid.Rows.Count > 0)
{
GridView1.Datasource = dtgrid;
GridView1.DataBind();
Here is whole code in CODE BEHIND .aspx.cs Page Code -
14. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
14
}
else
{
string strmsg = “No records found.”;
ClientScript.RegisterStartupScript(this.GetType(), “alert”, “alert(‘” + strmsg + “’)”, true);
}
}
public void GetTotalCount()
{
int count=0;
try{
DataTable dtcount = new DataTable();
dtcount = null;
clsUsers objclass = new clsUsers();
dtcount = objclass.getcount();
if (dtcount != null && dtcount.Rows.Count > 0)
{
count=int.Parse(dtcount.Row[0][“count”].ToString());
}
}
catch(Exception ex)
{
}
return count;
}
}
}
Set Connection String of database in web.config -
<add name=”ConnectionStringSAM” connectionString=”server=.;database=db_Test;user
id=sa;password=hDA4Wyu3qqtDuFA” providerName=”System.Data.SqlClient”/>
15. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
15
Now Build this application and run it - It will show GridView with paging and It will display data for 0 index
as-
UserID UserName UserType ContactNo EmailID Gender
1 User1 Admin 9999999999 abc@abc.com Male
2 User2 Clerk 9999999999 abc@abc.com Male
3 User3 Execeutive 9999999999 abc@abc.com Male
4 User4 Execeutive 9999999999 abc@abc.com Male
5 User5 Execeutive 9999999999 abc@abc.com Female
6 User6 Execeutive 9999999999 abc@abc.com Male
7 User7 Execeutive 9999999999 abc@abc.com Male
8 User8 Execeutive 9999999999 abc@abc.com Male
9 User9 Manager 9999999999 abc@abc.com Male
10 User10 TeamLead 9999999999 abc@abc.com Male
First Previous Next Last
16. CUSTOM PAGING INSIDE GRIDVIEW IN ASP.NET 4.5
16
info@tothenew.comwww.tothenew.com
LET’S CONNECT
We are TO THE NEW Digital, a premium digital services company that uniquely combines the power of
technology, analytics, creative and content for digital transformation.
Our passionate team of over 600 people includes technology evangelists, social media experts, content
specialists, and creative mavericks who have transformed businesses of more than 300 companies spread
across 30 countries worldwide.
ABOUT TO THE NEW DIGITAL