DataGrid Sorting and Paging Example – Part 2

For Part 1, visit This URL https://jitendrazaa.com/blog/?p=191

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();
try
{
con = new SqlConnection(conString);
con.Open();
adp = new SqlDataAdapter("Select * from Employee",con);
adp.Fill(dt);
return dt;
}
catch (CustomException ex)
{
ex.logException();
}finally{
con.Close();
}
return null;
}

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

The format for sorting the grid is like:

SortExpression+”asc”

OR

SortExpression+”desc”

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;
}
else
{
string oldSortExp = Session["OldSortDir"].ToString();
if (oldSortExp == "asc")
{
dir = "desc";
Session["OldSortDir"] = "desc";
}
else
{
dir = "asc";
Session["OldSortDir"] = "asc";
}
}
dv.Sort = e.SortExpression+"  "+dir;
}
grdEmp.DataSource = dv;
grdEmp.DataBind();
}

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;
BindTable();
}

Download Source code

Posted

in

by


Related Posts

Comments

Leave a Reply

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

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading