views:

280

answers:

1

I have read many posts on this topic; among them and most recently .NET - Convert Generic Collection to Data Table. Unfortunately, all to no avail.

I have a generic collection 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 fill a DataTable with this list of structures but have no idea how to go about doing this. I am using vb.net in Visual Studio 2008.

Any insights will be greatly appreciated

A: 

The code you linked assumes the members are declared as properties. You didn't declare properties. 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
Hans Passant
nobugz, thank you for such a prompt response! I added this function to my class, then passed it the list of structures (oTable = ConvertToDataTable(LOStates)) but no rows were retruned - the table count = 0 before being returned to where it was called from. I'm wondering if there's something else that I'm missing or doing incorrectly...
8thWonder
Debug it. Do the for each loops loop? Does the table have any columns?
Hans Passant
It was in debug that I was able to determine that the table count = 0. The for each loops loop indeed. There are 3 coumns but 0 rows right before the return table statement is executed.
8thWonder
I forgot to add the row to the table. I updated the code snippet.
Hans Passant
I noticed that as soon as I finished typing my last response so I included the add statement. BUT after adding the first row to the DataTable, it craps out citing a "System.Reflection.TargetInvocationException" befor going on to add any more rows to teh DataTable.
8thWonder
Sorry for being such a pain in the tail! I really appreciate your help and patience :)
8thWonder
Oh nvm, I effed up w/ the declarations! It's all good. You're the man nobugz!
8thWonder