DataGrid Sorting and Paging Example – Part 2

For Part 1, visit This URL

In this part, i will show that how to Sort the Datagrid Component of ASP.NET.

To sort Datagrid, we will need DataView and then assign Dataview as datasource to our Grid control.

We will need to change our code of Part 1.

Previously, we used DataSet as a Datasource. This time we will use DataTable and get the DataView from DataTable using below line.

DataView dv = dt.DefaultView; //Where dt id DataTable

So we have created a function, which will return the DataTable as shown below:

private DataTable GetTableFromDataBase()
SqlConnection con = null;
SqlDataAdapter adp = null;
DataTable dt = new DataTable();
con = new SqlConnection(conString);
adp = new SqlDataAdapter("Select * from Employee",con);
return dt;
catch (CustomException ex)
return null;

we will need to create the function on Sortcommand of the DataGrid.

The format for sorting the grid is like:




Below is the code snap used for the sorting:

protected void grdEmp_Sort(object source, DataGridSortCommandEventArgs e)
DataTable dt = GetTableFromDataBase();
DataView dv = dt.DefaultView;
string dir = string.Empty;
if (e.SortExpression.Length > 0)
if (Session["OldSortDir"] == null)
Session["OldSortDir"] = e.SortExpression;
string oldSortExp = Session["OldSortDir"].ToString();
if (oldSortExp == "asc")
dir = "desc";
Session["OldSortDir"] = "desc";
dir = "asc";
Session["OldSortDir"] = "asc";
dv.Sort = e.SortExpression+"  "+dir;
grdEmp.DataSource = dv;

The code for the Pagination is written below. Consider Page Size as 3.

protected void grdEmp_Paging(object source,DataGridPageChangedEventArgs p)
grdEmp.CurrentPageIndex = p.NewPageIndex;

Download Source code

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.