Sort Asp.Net GridView Column

Well, it’s a very simple feature, still if you forget it, it may cause you unnecessary trouble. So here’s the code for it.

Here, I will create a custom property of type SortDirection.
Now on GridView’s Sorting event, I will check the ViewState – sortDirection value and accordingly I will sort the given Column.

DataTable dt = ((DataSet)ViewState[“ClientDetails”]).Tables[0];
DataView dView = new DataView(dt);

if (GridViewSortDirection == SortDirection.Ascending)
	GridViewSortDirection = SortDirection.Descending;
	dView.Sort = e.SortExpression + ” DESC”;
	GridViewSortDirection = SortDirection.Ascending;
	dView.Sort = e.SortExpression + ” ASC”;
grdView1.DataSource = dView;

And we also need to declare the property GridViewSortDirection of type SortDirection. which will declare the ViewState – sortDirection as Ascending for the page if its value is found to be null.

public SortDirection GridViewSortDirection
		if (ViewState[“sortDirection”] == null)
		ViewState[“sortDirection”] = SortDirection.Ascending;
		return (SortDirection)ViewState[“sortDirection”];
		ViewState[“sortDirection”] = value;

That’s it!!!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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