Thursday, August 12, 2010

Custom Sorting with GridView Control | Handling GridView Sorting Event

Custom Sorting with GridView Control, Handling GridView Sorting Event

Bind a grid, and Set SortExpresion property for the particular field to be sortable (Eg, BoundField).
In the following example coulmn name is assigned to SortExpression property. I have a table with column with country; I need to sort records in ascending and descending order based on the country.

In the following example you can see three methods:

1. GridView1_Sorting :  GridView's Sorting event handling method.

2. Sort : implementation of sort logic

3. ManageViewState : To keep current sorting order.

#region Sort

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)

void Sort(string column)

case "Country":

if (ViewState[column] == null)
reportsSorted = (from r in report orderby r.Country ascending select r).ToList();

reportsSorted = (from r in report orderby r.Country descending select r).ToList();
ManageViewState(column, false);



void ManageViewState(string key, bool Tokeep)
if (Tokeep)
    ViewState[key] = true;
else if(ViewState[key]!=null)


Have a look at above code and try to work out it.