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.

4 comments:

  1. This is one of the best solutions I've seen so far that doesn't involve a lot of jumping through hoops in order to set up a special IComparer class just for the sorting of your GridView.

    One question, though: where do you get and store the CurrentSortDirection? You pull that value out of the air above. The value in e.SortDirection shows the direction for the current sort, but I don't know how to tell the GridView what the next sort direction should be.

    Thanks!

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Hi Derek,
      In this sample I've put CurrentSortDirection as a property in session. Now you can choose whatever suits you most as long as you keep CurrentSortDirection persistent (post backs) eg. Session, ViewState, control attribute, hidden fields..

      Good to hear you liked it.

      Delete
  2. Perfect!! But I must add .ToList() to .myGridView.DataSource

    ReplyDelete