Earlier I posted about how to dynamically sort the data using extension method see this http://www.noesispedia.com/post/2008/03/21/Linq-to-Sql-Dynamic-Sorting-without-using-Complete-Dynamic-Linq-Libraries.aspx
In this post I will present a quick solution to sort a list of object based on a property of object.
Suppose you have an object like
1:
2: public class MockObj
3: {
4: prop a
5: prop b
6: prop c
7: prop d
8: }
If you are binding above object with gridview (List) and you want to enable sorting in gridview onsorted event use following code to sort
1:
2: protected void gv_OnSorting(object sender, GridViewSortEventArgs e)
3: {
4: if (SortDirection == SortDirection.Ascending)
5: ((GridView)sender).DataSource = List.OfType().OrderBy(mo=> mo.GetType().GetProperty(e.SortExpression).GetValue(mo, null));
6: else
7: ((GridView)sender).DataSource = List.OfType().OrderByDescending(mo=> mo.GetType().GetProperty(e.SortExpression).GetValue(mo, null));
8: SortDirection = SortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
9: ((GridView)sender).DataBind();
10: }
Note that sortExpression specified in gridview must match with one of the property on the object.
If you don't want to use this quick but dirty solution you can go for extension methods. For more information see following links
http://mironabramson.com/blog/post/2008/05/Sorting-a-collection-using-sort-expression-string.aspx
http://www.singingeels.com/Articles/Self_Sorting_GridView_with_LINQ_Expression_Trees.aspx
Thanks to my friend Joseph for giving this solution and saving time in writing case statements :-)
Hope this helps!
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5