ListView with AutoColumns

Monday, December 07, 2009 10:00:10 PM (GMT Standard Time, UTC+00:00)

When you are prototyping it is nice to get things up and running quickly.  The other day I was using the DataGrid to prototype some work I am doing and it just so happened the result sets were rather large.  I like the fact that the DataGrid can dynamically create columns on the fly… but with large working sets of data, it takes longer to render then a GridView.

With that, I created a simple mechanism that will auto generate the GridView for you through reflection. Set the returning GridView to the View property on the ListView. Here are the helper calls:

public class GridViewHelper
   {
       /// <summary>
       /// Auto generates a GridView based on public properties in an object.
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <returns></returns>
       public static GridView AutoGridView<T>()
       {
           GridView view = new GridView();
 
           foreach (PropertyInfo info in typeof(T).GetProperties())
           {
               GridViewColumn gridViewColumn = GenerateGridViewColumn(info.Name);
               view.Columns.Add(gridViewColumn);
           }
 
           return view;
       }
 
       /// <summary>
       /// Auto generates a GridView based on public properties in an instance of an object.
       /// </summary>
       /// <param name="instance">The instance.</param>
       /// <returns></returns>
       public static GridView AutoGridView(object instance)
       {
           GridView view = new GridView();
 
           foreach (PropertyInfo info in instance.GetType().GetProperties())
           {
               GridViewColumn gridViewColumn = GenerateGridViewColumn(info.Name);
               view.Columns.Add(gridViewColumn);
           }
 
           return view;
       }
 
       /// <summary>
       /// Generates the grid view column based on a property name
       /// </summary>
       /// <param name="propName">Name of the prop.</param>
       /// <returns></returns>
       private static GridViewColumn GenerateGridViewColumn(string propName)
       {
           GridViewColumn gridViewColumn = new GridViewColumn();
           gridViewColumn.Header = propName;
           gridViewColumn.DisplayMemberBinding = new Binding(propName);
           return gridViewColumn;
       }
 
       /// <summary>
       /// Define the Property Names you want to show in the Grid.
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <param name="columns">The columns.</param>
       /// <returns></returns>
       public static GridView AutoGridView(params string[] columns)
       {
           GridView view = new GridView();
 
           foreach (string propName in columns)
           {
               GridViewColumn gridViewColumn = GenerateGridViewColumn(propName);
               view.Columns.Add(gridViewColumn);
           }
 
           return view;
       }
   }