1. Add using statement:
using System.Linq.Expressions; 2. Define your gridview and set the event “onsorting”.
<asp:GridView ID="myGridView" runat="server"...
onsorting="gridView_Sorting">
3. Set up your sorting method:
protected void gridView_Sorting(object sender, GridViewSortEventArgs e){
//Get the datasource and last sortDirection (enum (int) in this case):
List<YourObject> yourObjects = CurrentDataSource;
int currentSortDirection = CurrentSortDirection;
if (yourObjects != null)
{
//Use the e.SortExpression to order the list of objects
var param = Expression.Parameter(typeof(YourObject), e.SortExpression);
var sortExpression = Expression.Lambda<Func<YourObject, object>>(Expression.Convert(Expression.Property(param, e.SortExpression), typeof(object)), param);
//Set the list ordered ascending as datasource
if (currentSortDirection == (int)SortDirection.ascending)
{
myGridView.DataSource = yourObjects.AsQueryable<YourObject>().OrderBy(sortExpression);
}
//Set the list ordered descending as datasource
else
{
myGridView.DataSource = yourObjects.AsQueryable<YourObject>().OrderByDescending(sortExpression);
}
if (currentSortDirection == (int)SortDirection.ascending)
CurrentSortDirection = (int)SortDirection.descending;
else
CurrentSortDirection = (int)SortDirection.ascending;
myGridView.DataBind();
}
}
4. Your all set. Good luck.