I had a similar problem with a Listview control. I decided it like that.
first, I use the code from this post Marc Gravell Dynamic LINQ OrderBy on IEnumerable <T>
in my ListView 'OnSorting' event, I added the following code.
protected void lv_Sorting(object sender, ListViewSortEventArgs e) { e.Cancel = true; ViewState["OrderBy"] = e.SortExpression; lvList.DataBind(); }
I added a pretty standard way to grab the sortidirection this list.
public SortDirection sortDirection { get { if (ViewState["sortdirection"] == null) { ViewState["sortdirection"] = SortDirection.Ascending; return SortDirection.Ascending; } else if ((SortDirection)ViewState["sortdirection"] == SortDirection.Ascending) { ViewState["sortdirection"] = SortDirection.Descending; return SortDirection.Descending; } else { ViewState["sortdirection"] = SortDirection.Ascending; return SortDirection.Ascending; } } set { ViewState["sortdirection"] = value; } }
In my Listview, the Selectmethod looks like this (using the extension method from Marc)
public IQueryable<SomeObject> GetObjects([ViewState("OrderBy")]String OrderBy = null) { var list = GETSOMEOBJECTS(); if (OrderBy != null) { switch (sortDirection) { case SortDirection.Ascending: list = list.OrderByDescending(OrderBy); break; case SortDirection.Descending: list = list.OrderBy(OrderBy); break; default: list = list.OrderByDescending(OrderBy); break; } } return list; }
I have not tried it with GridView, but I am sure that it will work the same.
EDIT The following is an example linq extension class that should work
public static class LinqExtensions { public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderBy"); } public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderByDescending"); } public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenBy"); } public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenByDescending"); } static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName) { string[] props = property.Split('.'); Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; foreach (string prop in props) {
Just add "anynamespaceyouused" to the page and you should be good to go.