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”;
}
else
{
	GridViewSortDirection = SortDirection.Ascending;
	dView.Sort = e.SortExpression + ” ASC”;
}
grdView1.DataSource = dView;
grdView1.DataBind();

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
{
	get
	{
		if (ViewState[“sortDirection”] == null)
		ViewState[“sortDirection”] = SortDirection.Ascending;
		return (SortDirection)ViewState[“sortDirection”];
	}
	set
	{
		ViewState[“sortDirection”] = value;
	}
}

That’s it!!!

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s