HOW TO: Using sorting on GridView without a DataSourceControl

Sometimes you need to sorting a GridView manually because you don’t have a datasourcecontrol, then you need to handle the Sorting event of the Grid View. The bad thing is you have to use ViewState  to keep the last state that was sorted. I don’t know, but I think if was possible to set up the GridView.SortDirection property after sorted the DataView in this case, we didn’t need to use ViewState, but the GridView.SortDirection is readonly.

Here is the code:


private string ConvertSortDirectionToSql(SortDirection sortDirection)
{

string newSortDirection = string.Empty;

switch (sortDirection) {
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}

protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = GridView.DataSource as DataTable;

string previousSortExpression=(string)ViewState["previousGVSortKey"];
string sortExpression=e.SortExpression;
SortDirection sortDirection = e.SortDirection;

if (sortExpression.Equals(previousSortExpression))
{
sortDirection = SortDirection.Descending;
ViewState["previousGVSortKey"] = string.Empty;
}
else {
ViewState["previousGVSortKey"] = sortExpression;
}

if (dataTable != null) {
DataView dataView = new DataView(dataTable);
dataView.Sort = sortExpression + " " + ConvertSortDirectionToSql(sortDirection);

GridView.DataSource = dataView;
GridView.DataBind();
}
}

I had create a new post about the same subject but is using Lit<object> as a datasource, take a look:

HOW TO: Sort a GridView using List as a datasource

One thought on “HOW TO: Using sorting on GridView without a DataSourceControl

Leave a comment