Wednesday, May 23, 2012

Convert a MyClass array into DataTable

Using Relfection and Generics is possible to convert (or transform) an array of classes into a DataTable:


Imports System.Reflection


Public Shared Function convertFromClassToDatatable(Of T)(ByVal tableName As String, ByVal datas As T(), ByVal withHeader As Boolean) As DataTable

    Dim dt As New DataTable
    dt.TableName = tableName

    For Each prop As PropertyInfo In GetType(T).GetProperties
        dt.Columns.Add(prop.Name)
    Next

    If withHeader Then
        Dim drHeader As DataRow = dt.NewRow
        For Each col As DataColumn In dt.Columns
            drHeader.Item(col.ColumnName) = col.ColumnName.ToUpper
        Next
        dt.Rows.Add(drHeader)
    End If

    For Each data As T In datas 
        Dim dr As DataRow = dt.NewRow

        For Each prop As PropertyInfo In GetType(T).GetProperties
            dr.Item(dt.Columns.IndexOf(prop.Name)) = prop.GetValue(data, Nothing)
        Next

        dt.Rows.Add(dr)
    Next

    Return dt
End Function


Usage:

Dim myArray As myClass()

convertFromClassToDatatable("Test Table"),  myArray, False)



Note: 
Siccome vengono utilizzati i Generics, in automatico il sistema sa che classe è "dati", che viene passata alla funzione. 
La DataTable risultante avrà TableName = tableName e i vari ColumnName saranno i nomi delle proprietà della classe "miaClasse"

No comments: