How to do Grid view sorting

The following code sample shows how to do sorting in grid view


protected void gridView_Sorting(object sender, GridViewSortEventArgs e)

{

DataTable dataTable = grid.DataSource as DataTable;

if (dataTable != null)

{

DataView dataView = new DataView(dataTable);

dataView.Sort = GetSortExpression(e.SortExpression);

grid.DataSource = dataView;

grid.DataBind();

}

}

private string GetSortExpression(string sortExpression)
{

if (sortExpression == GridViewSortExpression && GridViewSortDirection == "ASC")

{

GridViewSortDirection = "DESC";

}

else

{

GridViewSortDirection = "ASC";

}

GridViewSortExpression = sortExpression;

return sortExpression + " " + GridViewSortDirection;


Comments

Author: Kapil Dhawan17 Jun 2008 Member Level: Gold   Points : 2

Hello
Nice piece of code
Thanks for sharing your knowledge with us.
I hope to see more good code from your side
This code is going to help lots of guys.
Ton Thanks to you
Regards,
Kapil

Author: Phani17 Jun 2008 Member Level: Silver   Points : 1

hi... Thanks for posting this type code snippet and this is very useful for me keep posting this type of snippets

Author: Phagu Mahato23 Jan 2014 Member Level: Gold   Points : 7

Thank for posting useful article about Grid view sorting. Now I post some more sample code

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
listBindByName();
DataSet datasortTable = GridView1.DataSource as DataSet;
DataTable dtSortTable = datasortTable.Tables[0];
if (dtSortTable != null)
{
DataView dvSortedView = new DataView(dtSortTable);
dvSortedView.Sort = e.SortExpression + " " + getExamplesortDirectionString();
ViewState["sortExpression"] = e.SortExpression;
GridView1.DataSource = dvSortedView;
GridView1.DataBind();
}
UpdatePanel1.Update();
}

private string getExamplesortDirectionString()
{
if (ViewState["ExamplesortDirection"] == null)
{
ViewState["ExampleExamplesortDirection"] = "ASC";
}
else
{
if (ViewState["ExamplesortDirection"].ToString() == "ASC")
{
ViewState["ExamplesortDirection"] = "DESC";
return ViewState["ExamplesortDirection"].ToString();
}
if (ViewState["ExamplesortDirection"].ToString() == "DESC")
{
ViewState["ExamplesortDirection"] = "ASC";
return ViewState["ExamplesortDirection"].ToString();
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: