SlideShare a Scribd company logo
1 of 16
Download to read offline
CUSTOM PAGING
WITH GRID VIEW5
VISHWADEEP MAHESHWARI,
LEAD, MARTECH SERVICES
AUGUST 2015
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.
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.
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.
}
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.
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;
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”))
{
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();
}
}
}
}
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.
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)
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 -
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;
}
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 -
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”/>
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
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

More Related Content

What's hot

Big query the first step - (MOSG)
Big query the first step - (MOSG)Big query the first step - (MOSG)
Big query the first step - (MOSG)Soshi Nemoto
 
Google BigQuery for Everyday Developer
Google BigQuery for Everyday DeveloperGoogle BigQuery for Everyday Developer
Google BigQuery for Everyday DeveloperMárton Kodok
 
Big Data London v 11.0 I 'Distributed Machine & Deep Learning at Scale with A...
Big Data London v 11.0 I 'Distributed Machine & Deep Learning at Scale with A...Big Data London v 11.0 I 'Distributed Machine & Deep Learning at Scale with A...
Big Data London v 11.0 I 'Distributed Machine & Deep Learning at Scale with A...Dataconomy Media
 
Introducing AWS AppSync: serverless data driven apps with real-time and offli...
Introducing AWS AppSync: serverless data driven apps with real-time and offli...Introducing AWS AppSync: serverless data driven apps with real-time and offli...
Introducing AWS AppSync: serverless data driven apps with real-time and offli...Amazon Web Services
 
Data Science using Google Cloud BigQuery, Python and Power BI
Data Science using Google Cloud BigQuery, Python and Power BIData Science using Google Cloud BigQuery, Python and Power BI
Data Science using Google Cloud BigQuery, Python and Power BIMarcelo Gazzola Ribeiro
 
Supercharging Applications with GraphQL and AWS AppSync
Supercharging Applications with GraphQL and AWS AppSyncSupercharging Applications with GraphQL and AWS AppSync
Supercharging Applications with GraphQL and AWS AppSyncAmazon Web Services
 
Intershop Commerce Management with Microsoft SQL Server
Intershop Commerce Management with Microsoft SQL ServerIntershop Commerce Management with Microsoft SQL Server
Intershop Commerce Management with Microsoft SQL ServerMauro Boffardi
 
Firestore MENA digital days : GDG Abu dhabi
Firestore MENA digital days : GDG Abu dhabiFirestore MENA digital days : GDG Abu dhabi
Firestore MENA digital days : GDG Abu dhabiShashank Kakroo
 
BigQuery implementation
BigQuery implementationBigQuery implementation
BigQuery implementationSimon Su
 
Google BigQuery is the future of Analytics! (Google Developer Conference)
Google BigQuery is the future of Analytics! (Google Developer Conference)Google BigQuery is the future of Analytics! (Google Developer Conference)
Google BigQuery is the future of Analytics! (Google Developer Conference)Rasel Rana
 
PredictionIO - Scalable Machine Learning Architecture
PredictionIO - Scalable Machine Learning ArchitecturePredictionIO - Scalable Machine Learning Architecture
PredictionIO - Scalable Machine Learning Architecturepredictionio
 

What's hot (14)

BigQuery for Beginners
BigQuery for BeginnersBigQuery for Beginners
BigQuery for Beginners
 
Understanding angular meteor
Understanding angular meteorUnderstanding angular meteor
Understanding angular meteor
 
Big query the first step - (MOSG)
Big query the first step - (MOSG)Big query the first step - (MOSG)
Big query the first step - (MOSG)
 
Google BigQuery for Everyday Developer
Google BigQuery for Everyday DeveloperGoogle BigQuery for Everyday Developer
Google BigQuery for Everyday Developer
 
Big Data London v 11.0 I 'Distributed Machine & Deep Learning at Scale with A...
Big Data London v 11.0 I 'Distributed Machine & Deep Learning at Scale with A...Big Data London v 11.0 I 'Distributed Machine & Deep Learning at Scale with A...
Big Data London v 11.0 I 'Distributed Machine & Deep Learning at Scale with A...
 
Introducing AWS AppSync: serverless data driven apps with real-time and offli...
Introducing AWS AppSync: serverless data driven apps with real-time and offli...Introducing AWS AppSync: serverless data driven apps with real-time and offli...
Introducing AWS AppSync: serverless data driven apps with real-time and offli...
 
Data Science using Google Cloud BigQuery, Python and Power BI
Data Science using Google Cloud BigQuery, Python and Power BIData Science using Google Cloud BigQuery, Python and Power BI
Data Science using Google Cloud BigQuery, Python and Power BI
 
Supercharging Applications with GraphQL and AWS AppSync
Supercharging Applications with GraphQL and AWS AppSyncSupercharging Applications with GraphQL and AWS AppSync
Supercharging Applications with GraphQL and AWS AppSync
 
Google BigQuery
Google BigQueryGoogle BigQuery
Google BigQuery
 
Intershop Commerce Management with Microsoft SQL Server
Intershop Commerce Management with Microsoft SQL ServerIntershop Commerce Management with Microsoft SQL Server
Intershop Commerce Management with Microsoft SQL Server
 
Firestore MENA digital days : GDG Abu dhabi
Firestore MENA digital days : GDG Abu dhabiFirestore MENA digital days : GDG Abu dhabi
Firestore MENA digital days : GDG Abu dhabi
 
BigQuery implementation
BigQuery implementationBigQuery implementation
BigQuery implementation
 
Google BigQuery is the future of Analytics! (Google Developer Conference)
Google BigQuery is the future of Analytics! (Google Developer Conference)Google BigQuery is the future of Analytics! (Google Developer Conference)
Google BigQuery is the future of Analytics! (Google Developer Conference)
 
PredictionIO - Scalable Machine Learning Architecture
PredictionIO - Scalable Machine Learning ArchitecturePredictionIO - Scalable Machine Learning Architecture
PredictionIO - Scalable Machine Learning Architecture
 

Viewers also liked

Fotografias increibles
Fotografias increiblesFotografias increibles
Fotografias increiblesBeatris Lopes
 
Ncdex marrket news for 30 aug
Ncdex marrket news for 30 augNcdex marrket news for 30 aug
Ncdex marrket news for 30 augRehana Kapoor
 
Acc webinar deploying act! in a citrix environment
Acc webinar deploying act! in a citrix environmentAcc webinar deploying act! in a citrix environment
Acc webinar deploying act! in a citrix environmentJon Klubnik
 
Butterfly ping pong
Butterfly ping pongButterfly ping pong
Butterfly ping pongrichard896
 
Table tennis ball price
Table tennis ball priceTable tennis ball price
Table tennis ball pricerichard896
 

Viewers also liked (8)

Audience Survey
Audience SurveyAudience Survey
Audience Survey
 
Fotografias increibles
Fotografias increiblesFotografias increibles
Fotografias increibles
 
Ncdex marrket news for 30 aug
Ncdex marrket news for 30 augNcdex marrket news for 30 aug
Ncdex marrket news for 30 aug
 
Acc webinar deploying act! in a citrix environment
Acc webinar deploying act! in a citrix environmentAcc webinar deploying act! in a citrix environment
Acc webinar deploying act! in a citrix environment
 
Butterfly ping pong
Butterfly ping pongButterfly ping pong
Butterfly ping pong
 
Table tennis ball price
Table tennis ball priceTable tennis ball price
Table tennis ball price
 
Equipo 2 . Sandra and Verónica. Prizes.
Equipo 2 . Sandra and Verónica. Prizes.Equipo 2 . Sandra and Verónica. Prizes.
Equipo 2 . Sandra and Verónica. Prizes.
 
Superba grecie
Superba grecieSuperba grecie
Superba grecie
 

Similar to Custom Paging with GridView

Step by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView TutorialsStep by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView TutorialsNilesh kumar Jadav
 
How to add sorting and pagers to grid view
How to add sorting and pagers to grid viewHow to add sorting and pagers to grid view
How to add sorting and pagers to grid viewDharma Raju
 
Streamlining data analysis through environmental alerts how to integrate ambe...
Streamlining data analysis through environmental alerts how to integrate ambe...Streamlining data analysis through environmental alerts how to integrate ambe...
Streamlining data analysis through environmental alerts how to integrate ambe...Ambee
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Robert DeLuca
 
Effective Android Data Binding
Effective Android Data BindingEffective Android Data Binding
Effective Android Data BindingEric Maxwell
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library 10Clouds
 
Agile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansAgile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansCarol McDonald
 
Data Binding in Action using MVVM pattern
Data Binding in Action using MVVM patternData Binding in Action using MVVM pattern
Data Binding in Action using MVVM patternFabio Collini
 
Deep dive into Android Data Binding
Deep dive into Android Data BindingDeep dive into Android Data Binding
Deep dive into Android Data BindingRadek Piekarz
 
Implement react pagination with react hooks and react paginate
Implement react pagination with react hooks and react paginateImplement react pagination with react hooks and react paginate
Implement react pagination with react hooks and react paginateKaty Slemon
 
Whats New for WPF in .NET 4.5
Whats New for WPF in .NET 4.5Whats New for WPF in .NET 4.5
Whats New for WPF in .NET 4.5Rainer Stropek
 
Grails EE
Grails EEGrails EE
Grails EEGR8Conf
 
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...Infinum
 
ASP.NET Session 13 14
ASP.NET Session 13 14ASP.NET Session 13 14
ASP.NET Session 13 14Sisir Ghosh
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesMichael Galpin
 
Data Binding - Android by Harin Trivedi
Data Binding - Android by Harin TrivediData Binding - Android by Harin Trivedi
Data Binding - Android by Harin Trivediharintrivedi
 

Similar to Custom Paging with GridView (20)

GRID VIEW PPT
GRID VIEW PPTGRID VIEW PPT
GRID VIEW PPT
 
70562 (1)
70562 (1)70562 (1)
70562 (1)
 
Step by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView TutorialsStep by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView Tutorials
 
How to add sorting and pagers to grid view
How to add sorting and pagers to grid viewHow to add sorting and pagers to grid view
How to add sorting and pagers to grid view
 
Streamlining data analysis through environmental alerts how to integrate ambe...
Streamlining data analysis through environmental alerts how to integrate ambe...Streamlining data analysis through environmental alerts how to integrate ambe...
Streamlining data analysis through environmental alerts how to integrate ambe...
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React
 
Effective Android Data Binding
Effective Android Data BindingEffective Android Data Binding
Effective Android Data Binding
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library
 
Agile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansAgile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with Netbeans
 
Data Binding in Action using MVVM pattern
Data Binding in Action using MVVM patternData Binding in Action using MVVM pattern
Data Binding in Action using MVVM pattern
 
Deep dive into Android Data Binding
Deep dive into Android Data BindingDeep dive into Android Data Binding
Deep dive into Android Data Binding
 
Implement react pagination with react hooks and react paginate
Implement react pagination with react hooks and react paginateImplement react pagination with react hooks and react paginate
Implement react pagination with react hooks and react paginate
 
Sign in
Sign inSign in
Sign in
 
Whats New for WPF in .NET 4.5
Whats New for WPF in .NET 4.5Whats New for WPF in .NET 4.5
Whats New for WPF in .NET 4.5
 
Grails EE
Grails EEGrails EE
Grails EE
 
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
Infinum Android Talks #14 - Data binding to the rescue... or not (?) by Krist...
 
ASP.NET Session 13 14
ASP.NET Session 13 14ASP.NET Session 13 14
ASP.NET Session 13 14
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and Smartphones
 
Ch05 state management
Ch05 state managementCh05 state management
Ch05 state management
 
Data Binding - Android by Harin Trivedi
Data Binding - Android by Harin TrivediData Binding - Android by Harin Trivedi
Data Binding - Android by Harin Trivedi
 

Recently uploaded

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 

Recently uploaded (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 

Custom Paging with GridView

  • 1. CUSTOM PAGING WITH GRID VIEW5 VISHWADEEP MAHESHWARI, LEAD, MARTECH SERVICES AUGUST 2015
  • 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