Step 1 :First Create one Entity
public class OLRFormDetails
{
public string firstName { get; set; }
public string middileName { get; set; }
public string lastName { get; set; }
public string fatherName { get; set; }
public string DOJ { get; set; }
public string DOB { get; set; }
public string resumeID { get; set; }
public string gender { get; set; }
}
Step 2: Add below methods
public DataTable ConvertTo<T>(IList<T> lst)
{
DataTable tbl = CreateTable<T>();
Type entType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
foreach (T item in lst)
{
DataRow row = tbl.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
tbl.Rows.Add(row);
}
return tbl;
}
public DataTable CreateTable<T>()
{
Type entType = typeof(T);
DataTable tbl = new DataTable(entType.Name);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
foreach (PropertyDescriptor prop in properties)
tbl.Columns.Add(prop.Name, prop.PropertyType); return tbl;
}
Step 3:--
Create an object for class like below
OLRFormDetails olrDetails = null;
Create an object for generic list like this
List<OLRFormDetails> olrDetailslist = new List<OLRFormDetails>();
Add items to the list doing like this
olrDetailslist.Add(olrDetails);
After adding data you can convert the generic list in to datatable.
DataTable dt = ConvertTo<OLRFormDetails>(olrDetailslist);
Friday, November 9, 2012
Convert Generic List collection to DataTable in C#
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment