Using the following method you can convert the List into DataTable
For example you have the following List:
/// <summary>
/// RealTimeSalesInput
/// </summary>
public List<RealTimeSales> RealTimeSalesInput { get; set; }
/// <summary>
/// RealTimeSales
/// </summary>
public class RealTimeSales
{
public long StoreID { get; set; }
public string StoreNumber { get; set; }
public decimal Value { get; set; }
}
Now you can call the following function to provide the DataTable from the given List.
System.Collections.Generic.List<RealTimeSales> sales = new List<RealTimeSales>(){
new RealTimeSales() { StoreID = 100, StoreNumber = "A100", Value = 100 },
new RealTimeSales() { StoreID = 101, StoreNumber = "B100", Value = 101},
new RealTimeSales() { StoreID = 102, StoreNumber = "C100", Value = 102 }
};
System.Data.DataTable resultTable = ConvertToDataTableFromList(sales);
/// <summary>
/// Converts to data table from list.
/// Author: Himasagar Kutikuppala.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">The data.</param>
/// <returns></returns>
public DataTable ConvertToDataTableFromList<T>(IList<T> data)
{
System.Data.DataTable table = new System.Data.DataTable();
try
{
System.ComponentModel.PropertyDescriptorCollection props =
System.ComponentModel.TypeDescriptor.GetProperties(typeof(T));
for (int i = 0; i < props.Count; i++)
{
System.ComponentModel.PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
}
catch (Exception ex)
{
//Exception Occured
}
return table;
}