Showing posts with label Linq. Show all posts
Showing posts with label Linq. Show all posts

Tuesday, April 3, 2012

GridView, List of objects and sorting

Binding a GridView to a list of objects is a neat way to expose your data through Entity Framework. Now sorting a List of objects could be a bit tricky if you want it to be dynamic. In this scenario Linq and Lamdba offers great possibilities to achieve your goal.

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.