Wednesday, April 4, 2012

Quicktip of the day: Visual studio and clipboard (copy/paste)

Working with Visual Studio will give you both good and bad days. This tip may give you one or two more of the good ones.

Visual studio automatically stores your copy/cut commands up to 10 times. This means that you've not only the possibility to paste the last word that you copied or cut, but the 10 last ones.

To use this feature simply use [Ctrl + Shift + V] instead of [Ctrl + V] and keep hitting to go back through your copy/cut history.

Enjoy!

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.