GridView control offers a cool property "EnableSortingAndPagingCallbacks" which enables the user to perform paging and sorting without any postbacks. Although the feature is pretty neat but it has some BIG limitations. First of all you can only use the DataSourceID property of the GridView to assign the data source. This rules out DataSets, DataTables and Custom Collections (My Favourite). So, only thing left for you to use is SqlDataSource and ObjectDataSource controls. When using SqlDataSource you basically have to do nothing simply assign the DataSourceID of the GridView to SqlDataSource control and that's it and also EnableSortingAndPagingCallbacks = true.
When using ObjectDataSource things get's little tricky. One easy way around is to return a DataView back to the client. The GetProductsUsingDataView can be used as the SelectMethod for the ObjectDataSource control.
public DataView GetProductsUsingDataView(string sortExpression)
string connectionString = @"Server=localhost;Database=Northwind;Trusted_Connection=true";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlCommand myCommand = new SqlCommand("SELECT ProductID, ProductName FROM Products", myConnection);
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
DataView dv = ds.Tables.DefaultView;
dv.Sort = sortExpression;
Another method is to keep track of the ascending and descending using the Session variable and alter the SQL query using the ORDER BY clause to get the ordered result. A better approach is to make use of the IComparer interface and implement a Generic IComparer to handle the sorting.
Stephane Schwartz wrote an excellent article about implementing the Generic Sort Method. You can check out the article at the following link: