How to populate a DataTable with a List (Of t) or convert a List (Of t) to a DataTable?

I read a lot of posts on this topic; among them, and more recently, .NET is converting a common collection into a data table . Unfortunately, all to no avail.

I have a common set of structures:

Private Structure MyStruct
Dim sState as String
Dim lValue as Long
Dim iLayer as Integer
End Structure

Dim LOStates As New List(Of MyStruct)

I need to populate a DataTable with this list of structures, but don't know how to do it. I am using vb.net in Visual Studio 2008.

Any ideas would be greatly appreciated.

+5
source share
2 answers

The code you link assumes the members are declared as properties. You have not declared a property. You can make it work with Reflection:

Imports System.Reflection
...

      Public Shared Function ConvertToDataTable(Of T)(ByVal list As IList(Of T)) As DataTable
        Dim table As New DataTable()
        Dim fields() As FieldInfo = GetType(T).GetFields()
        For Each field As FieldInfo In fields
          table.Columns.Add(field.Name, field.FieldType)
        Next
        For Each item As T In list
          Dim row As DataRow = table.NewRow()
          For Each field As FieldInfo In fields
            row(field.Name) = field.GetValue(item)
          Next
          table.Rows.Add(row)
        Next
        Return table
      End Function
+11

, @SamSelikoff, GetProperties:

Public Shared Function ConvertToDataTable(Of t)(
                                                  ByVal list As IList(Of t)
                                               ) As DataTable
    Dim table As New DataTable()
    If Not list.Any Then
        'don't know schema ....
        Return table
    End If
    Dim fields() = list.First.GetType.GetProperties
    For Each field In fields
        table.Columns.Add(field.Name, field.PropertyType)
    Next
    For Each item In list
        Dim row As DataRow = table.NewRow()
        For Each field In fields
            dim p = item.GetType.GetProperty(field.Name)
            row(field.Name) = p.GetValue(item, Nothing)
        Next
        table.Rows.Add(row)
    Next
    Return table
End Function
+1

All Articles