Sunday, February 7, 2010

Simple C# function to get the current sort direction of a column for GridView OnSorting Event.

I am going to provide you here with a very simple function to find out the sort direction for grid view column when sorting is implemented in the Grid.

You can use this function directly in your page.

ASP.Net provides every thing prepared for sorting in a GridView except for the sort direction for each column. We have to maintain it ourselves, however GridViewSortEventArgs.SortDirection does exist there but you may have find that everytime it returns value "Ascending", so it cannot be used.

So here is the function which will return you the current sort direction for a column. You can directly copy and paste the function. There is no need to pass column name in the function because we are creating a viewstate for each column.


public string GetSortDirection(string SortExpression)
{
if (ViewState[SortExpression] == null)
ViewState[SortExpression] = "Desc";
else
ViewState[SortExpression] = ViewState[SortExpression].ToString() == "Desc" ? "Asc" : "Desc";

return ViewState[SortExpression].ToString();
}


You can use it in the GridView OnSorting event like this



protected void GridView_OnSorting(object sender, GridViewSortEventArgs e)
{
string order = GetSortDirection(e.SortExpression);
string s = "select * from [User] order by " + e.SortExpression + " " + order;
BindGrid(s);
}


Where BindGrid() is the function which will bind your grid using the passed query.