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.
I think your code is missing something. Viewstate it is. Without Viewstate, you can't perform the sorting well.
ReplyDeleteFirstly, Thanks for the comment,
ReplyDeleteI have changed the code of my function little.
And as far as I know we need to store the last sort direction for a column so that you can get the current sort direction.
And viewstate should be the first choice for this.