Thursday, September 30, 2010

Grid View – Ilist & Dataset

we all know that with c# 3.5 & now 4, we have generics and LINQ – which makes it incredibly easy to Bind grid View to ilist that you get from a LINQ query when you use the entity data model.

However, After binding this data to Grid, you want to use the template columns to update the individual rows, also you want to save the data on post backs. I found that Ilist is not the best way to go (very much depends upon situation). Here the old friend – Dataset comes to rescue.

You can bind the dataset, Cache it and update the columns after every update. [ Think about this only for Selects] as you loose entity connections when you go the dataset way (There are ways to keep this dataset and entity in Sync but i will not talk about it now)

 

So, here is a small extension function to Ilist

[Uses Reflection ]

 

public static DataSet GetDataSet<T>( IList<T> list)
    {
        Type elementType = typeof(T);
        DataSet ds = new DataSet();
        DataTable t = new DataTable();
        ds.Tables.Add(t);

        //add a column to table for each public property on T
        foreach (var propInfo in elementType.GetProperties())
        {
            Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

            t.Columns.Add(propInfo.Name, ColType);
        }

        //go through each property on T and add each value to the table
        foreach (T item in list)
        {
            DataRow row = t.NewRow();

            foreach (var propInfo in elementType.GetProperties())
            {
                row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
            }

            t.Rows.Add(row);
        }

        return ds;
    }