Saturday, May 8, 2010

Converting “Var” to Dataset

After a long time back i’m into my blog…Didn’t get enough time to sit with the things..

In some cases we need to convert the anonymous datatype var to a dataset or datatable.we cant do it directly as so.Here is a

Simple method that will return the var or List item to dataset


public static DataSet ToDataSet(List list)
{

Type type = typeof(T);
DataSet ds = new DataSet("Company");
DataTable dt = new DataTable("Contacts");
ds.Tables.Add(dt);
//Dynamically adding columns to data table
foreach (var propInfo in type.GetProperties())
{
dt.Columns.Add(propInfo.Name, propInfo.PropertyType);

//You can add columns manually also here
if (propInfo.Name == "ID")
{
dt.Columns.Add("Photo");
}
}
foreach (T item in list)
{
DataRow dr = dt.NewRow();
foreach (var propInfo in type.GetProperties())
{
dr[propInfo.Name] = propInfo.GetValue(item, null);
}
dt.Rows.Add(dr);
}
return ds;
}

0 comments: