Introduction

This article talks about manually handling the sorting routine of a GridView control.   When using an object class as the Datasource for a GridView control in AbleCommerce, the GridView control will not automatically manage sorting.  This only works when using a SQL-based DataSourceObject.

So you’re left with creating your own method to handle the Sorting event on the GridView control.  Not so tough, there’s plenty of programming code examples in Google.   What’s harder to find is an example that actually retains the previous sort order for each column.

Enter:  e.SortDirection.  It’s exposed in the Sorting event, but you need a way to store the previous sort order for each column so the routine knows which way to flip it (Ascending or Descending).  If you don’t handle it, clicking a column always results in an Ascending sort order.

Here’s a good piece of code that makes nice use of Viewstate:

protected void ProductsGrid_Sorting(object sender, GridViewSortEventArgs e)

{

    if (e.SortExpression == (string)ViewState["SortColumn"])

    {

        // We are resorting the same column, so flip the sort direction

        e.SortDirection =

            ((SortDirection)ViewState["SortColumnDirection"] == SortDirection.Ascending) ?

            SortDirection.Descending : SortDirection.Ascending;

    }

    // Apply the sort

    BindProductsGrid(e.SortExpression, ConvertSortDirection(e.SortDirection));

    ViewState["SortColumn"] = e.SortExpression;

    ViewState["SortColumnDirection"] = e.SortDirection;

 

}