2009-11-26 62 views
5

我已閱讀關於此主題的許多帖子;其中包括最近的.NET - Convert Generic Collection to Data Table。不幸的是,一切都無濟於事。如何用列表(Of)填充DataTable或將列表(Of)轉換爲DataTable?

我有結構的泛型集合:

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

Dim LOStates As New List(Of MyStruct) 

我需要填寫與結構的此列表的DataTable,但不知道如何去這樣做。我使用vb.net在Visual Studio 2008中

任何見解將不勝感激

回答

11

您鏈接的代碼假定成員被聲明爲屬性。你沒有聲明屬性。你可以把它與反思工作:

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 
+0

nobugz,謝謝你,這麼迅速回應!我將這個函數添加到我的類中,然後將它傳遞給結構列表(oTable = ConvertToDataTable(LOStates)),但沒有重新生成行 - 表計數= 0,然後返回到從其調用的位置。我想知道是否有其他東西,我失蹤或做錯了... – 8thWonder 2009-11-27 16:57:19

+0

調試它。爲每個循環做循環?表格是否有任何列? – 2009-11-27 17:03:08

+0

它是在調試中,我能夠確定表計數= 0。確實爲每個循環循環。在執行return table語句之前有3個coumns,但有0行。 – 8thWonder 2009-11-27 18:36:40

1

我比@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