GridView sorting: SortDirection always Ascending

The problem with Session and Viewstate is that you also have to keep track of the gridview control for which SortColumn and Direction is stored if there is more than one gridview on the page.

An alternative to Session and Viewstate is to add 2 attributes to the Gridview and keep track of Column and Direction that way.

Here is an example:

private void GridViewSortDirection(GridView g, GridViewSortEventArgs e, out SortDirection d, out string f)
{
    f = e.SortExpression;
    d = e.SortDirection;

    //Check if GridView control has required Attributes
    if (g.Attributes["CurrentSortField"] != null && g.Attributes["CurrentSortDir"] != null)
    {
        if (f == g.Attributes["CurrentSortField"])
        {
            d = SortDirection.Descending;
            if (g.Attributes["CurrentSortDir"] == "ASC")
            {
                d = SortDirection.Ascending;
            }
        }

        g.Attributes["CurrentSortField"] = f;
        g.Attributes["CurrentSortDir"] = (d == SortDirection.Ascending ? "DESC" : "ASC");
    }

}

Leave a Comment