In this blog I described how to convert list objects to DataTable. There are several method to convert list objects to DataTable. In this blog I used List interface for conversion.
It is a generic method, it converts all types of list into DataTable. <T> defines the type of list.
In C#
Adding namespace:
using System.ComponentModel;
Generic method:
private DataTable ConvertToDataTable<T>(IList<T> list)
{
Type entityType = typeof(T);
DataTable table = new DataTable();
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(entityType);
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
In VB.NET:
Adding namespace:
Imports System.ComponentModel
Generic method:
Private Function ConvertToDataTable(Of T)(list As IList(Of T)) As DataTable
Dim entityType As Type = GetType(T)
Dim table As New DataTable()
Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(entityType)
For Each prop As PropertyDescriptor In properties
table.Columns.Add(prop.Name, If(Nullable.GetUnderlyingType(prop.PropertyType), prop.PropertyType))
Next
For Each item As T In list
Dim row As DataRow = table.NewRow()
For Each prop As PropertyDescriptor In properties
row(prop.Name) = If(prop.GetValue(item), DBNull.Value)
Next
table.Rows.Add(row)
Next
Return table
End Function
Hope this code will help you. Thanks
1 Comment(s)