Click here to Skip to main content
15,881,281 members
Articles / Web Development / ASP.NET
Article

Sorting and Paging of an Generic GridView

Rate me:
Please Sign up or sign in to vote.
2.65/5 (7 votes)
11 Jun 2008CPOL2 min read 54.8K   30   2
How to implement sorting and paging of an generic gridview

Introduction

This might be usefull if you would like to use hardcoded column names ... Most of the code is sourced from here: strong coders and here , so I quess I can't call my self author of this article, but more like wrapper producer ; )

Background

Separate presentation logic from data layer .... We asume here you have already your dataset, so I am not going to show .. how to populate it with values ... (for this one later one another article ; ) Using the code Just copy paste the code and play with it ... Here is the gridview in the aspx file

"table_list_gv" runat="server"
ToolTip="The list of projects matching your criteria" AccessKey="E"

CellPadding="4" BorderColor="#3366CC" Font-Size="Smaller"
HorizontalAlign="Left" BorderStyle="None" BorderWidth="1px" BackColor="White"
EnableViewState="true" EnableTheming="False"

AutoGenerateColumns="true"
PageIndex="0"
ActivePageIndex="0"
EmptyDataText="No records found"
PagerSettings-Mode="NumericFirstLast"
PageSize="3"
OnRowCreated="OnRowCreated"
AllowPaging="true" AllowSorting="true"
OnPageIndexChanging="Table_list_gv_PageIndexChanging"
OnSorting="Table_list_gv_Sorting"
OnRowDataBound="Table_list_gv_RowDataBound">

"#99CCCC" ForeColor="#003399">
"#003399" HorizontalAlign="Left" BackColor="#99CCCC">
"True" BackColor="#003399" BorderColor="#000066" BorderStyle="Solid" BorderWidth="1px"
Height="14px" HorizontalAlign="Center" VerticalAlign="Top" ForeColor="#CCCCFF" >

No reports were found with the supplied criteria

This is the method for creating the gridview Note: I do not create them in the page.aspx.cs files but throw the references ... so the following code should be called like this GUI.GUIHelper.PrepareSimpleGV ( ref msg , ref table_list_gv , ref rds ); (where GUI. is the name of the namespace I have those utilities ; ), the GUIHelper is the name of the Class containing the method and PrepareSimpleGV is the method - well you may be should have skipped this ; )

Here is a sample datapopulator method , just for the sake of the example:
						DataSet rds = new DataSet ();
						DataTable dt = new DataTable("myDynamicTable");
						// Create a DataColumn instances

						DataColumn dValue = new DataColumn();
						DataColumn dMember = new DataColumn();

						dValue.ColumnName = "Id";
						dValue.DataType = Type.GetType("System.Int32");
						
						dMember.ColumnName = "Name";
						dMember.DataType = Type.GetType("System.String");

						// Add these DataColumns into the DataTable
						dt.Columns.Add(dValue);
						dt.Columns.Add(dMember);



						for ( int i = 0 ; i<100 ; i++) 

						{

										DataRow dr = dt.NewRow();
										dr["Id"] = i;
										dr["Name"] = "Name " + System.Convert.ToString ( i ) ;

						// Add the row into the table

						dt.Rows.Add(dr);
						}
						rds.Tables.Add ( dt );
						
//store the dataset in a session variable to be able to use it when assigning the datasource
Session [ "pageName.rds" ] = rds;
} //eof method
public static void PrepareSimpleGV ( ref string msg , ref System.Web.UI.WebControls.GridView table_list_gv ,
ref System.Data.DataSet rds)
{
if (rds == null)
{ //just add an empty one in order to present the EmptyDataTemplate
rds = new DataSet ();
DataTable dt = new DataTable ();
rds.Tables.Add ( dt );
}
table_list_gv.DataSource = rds.Tables [ 0 ];
//debug Utils.Debugger.DebugDataSet ( "just after table_list_gv.DataSource = rds.Tables [ 0 ];" , ref rds );
table_list_gv.AllowPaging = true;
table_list_gv.AllowSorting = true;
table_list_gv.PageIndex = 0;
table_list_gv.EnableSortingAndPagingCallbacks = false;
table_list_gv.Visible = true;
table_list_gv.DataBind ();
return;

} //eof private static void PrepareSimpleGV(ref System.Web.UI.WebControls.GridView table_list_gv )

Now put the following Properties in your page.aspx.cs file :

 #region Properties

//===========================SORTING PROPERTIES START
private string GridViewSortDirection
{
get { return ViewState [ "SortDirection" ] as string ?? "ASC"; }
set { ViewState [ "SortDirection" ] = value; }
}

private string GridViewSortExpression
{
get { return ViewState [ "SortExpression" ] as string ?? string.Empty; }
set { ViewState [ "SortExpression" ] = value; }
}

private string GetSortDirection ()
{
switch (GridViewSortDirection)
{
case "ASC":
GridViewSortDirection = "DESC";
break;

case "DESC":
GridViewSortDirection = "ASC";
break;
}

return GridViewSortDirection;
}



//===========================SORTING PROPERTIES END

#endregion //Sorging and Paging Properties
The handlers for implementing the paging and sorting Now put those in the Methods region of your page.aspx.cs class:
//======================================== GRIDVIEW EventHandlers START
#region GridViewEventHandlers
protected void OnRowCreated ( object sender , GridViewRowEventArgs e )
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells [ 0 ].CssClass = "hiddencol";
}
else if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells [ 0 ].CssClass = "hiddencol";
}
} //eof protected void OnRowCreated ( object sender, GridViewRowEventArgs e )


protected void RowDataBound_Handler ( Object table_list_gv , GridViewRowEventArgs e )
{

} //eof method

protected void Table_list_gv_RowDataBound ( object sender , GridViewRowEventArgs e )
{

// apply custom formatting to data cells
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell cell;
// set formatting for the category cell
cell = e.Row.Cells [ 0 ];
cell.Width = new Unit ( "120px" );
cell.Style [ "border-right" ] = "3px solid #666666";
cell.BackColor = System.Drawing.Color.LightGray;

// set formatting for value cells
for (int i = 1; i < e.Row.Cells.Count; i++)
{
cell = e.Row.Cells [ i ];

// right-align each of the column cells after the first
// and set the width
cell.HorizontalAlign = HorizontalAlign.Right;
cell.Width = new Unit ( "90px" );

// alternate background colors
if (i % 2 == 1)
cell.BackColor
= System.Drawing.ColorTranslator.FromHtml ( "#EFEFEF" );

} //eof set formatting for value cells

} //eof if this is row


// apply custom formatting to the header cells
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell cell in e.Row.Cells)
{
cell.Style [ "border-bottom" ] = "3px solid #666666";
cell.BackColor = System.Drawing.Color.LightGray;
cell.ForeColor = System.Drawing.Color.Blue;
}
} //if (e.Row.RowType == DataControlRowType.Header)



} //eof protected void table_list_gv_RowDataBound ( object sender, GridViewRowEventArgs e )



protected void Table_list_gv_PageIndexChanging ( object sender , GridViewPageEventArgs e )
{
Session [ "reports.aspx.cs.SelectedIndexChanged" ] = 1;

table_list_gv.DataSource = SortDataTable ( table_list_gv.DataSource as DataTable , true );
table_list_gv.PageIndex = e.NewPageIndex;
table_list_gv.DataBind ();
//Session["ClickSearch"] = true;

} //EOF Table_list_gv_PageIndexChanging(object sender, GridViewPageEventArgs e)



protected DataView SortDataTable ( DataTable dataTable , bool isPageIndexChanging )
{

if (dataTable != null)
{
DataView dataView = new DataView ( dataTable );
if (GridViewSortExpression != string.Empty)
{
if (isPageIndexChanging)
{
dataView.Sort = string.Format ( "{0} {1}" , GridViewSortExpression , GridViewSortDirection );
}
else
{
dataView.Sort = string.Format ( "{0} {1}" , GridViewSortExpression , GetSortDirection () );
}
}
return dataView;
}
else
{
return new DataView ();
}
} //eof SortDataTable


protected void Table_list_gv_Sorting ( object sender , GridViewSortEventArgs e )
{
Session [ "reports.aspx.cs.SelectedIndexChanged" ] = 1;

GridViewSortExpression = e.SortExpression;
int pageIndex = table_list_gv.PageIndex;
table_list_gv.DataSource = SortDataTable ( table_list_gv.DataSource as DataTable , false );
table_list_gv.DataBind ();
table_list_gv.PageIndex = pageIndex;
} //eof table_list_gvSorting

#endregion //GridViewEventHandlers
//======================================== GRIDVIEW EventHandlers END

Points of Interest

Note, that the ViewState in the page should be enabled ... Note , that if you are getting the dataset from a stored procedure is always better to use select columnName as 'Nice Column Name for End User Reading ' .. Note , that I create the dynamic controls always earlier than in the page_load (for this one later another article ; ) Questions: Well how to disable programatically paging during run time ? and put it into the footer , or add another drop down for selecting the number of rows to display on a page ...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Oxit Oy
Finland Finland
I work in OXIT - a small IT consulting company, which has participated in the building of the most sophisticated IT Systems for several big Finnish and international companies (including Fortune 500 members) and continues to provide highly sophisticated IT Solutions to its customers.

I enjoy designing and implementing software or small scripts in different programming languages.

I am fascinated by the magic of software, which has the power to change the world.

Comments and Discussions

 
GeneralMinor points Pin
Mustafa Ismail Mustafa18-Apr-08 22:29
Mustafa Ismail Mustafa18-Apr-08 22:29 
GeneralFormatting needs attention Pin
leppie18-Apr-08 21:41
leppie18-Apr-08 21:41 

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.