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.
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
1 Comment(s)