How to tips and tricks for Microsoft Visual Studio .net

Thursday, August 23, 2012

Create a DataTable easily

I have a need to create Data Tables for many reasons in my quest for complete projects. If you need to do it, and you, like me, find the whole thing of defining each column and type a big schlep, check this out.
    Public Shared Function BuildDataTable(ByVal TableName As String,
ByVal Parameters As List(Of TableParams)) As DataTable
      Dim dtReturn As New DataTable(TableName)

      Try
        For Each param As TableParams In Parameters
          dtReturn.Columns.Add(New DataColumn(param.ColumnName, param.ColumnType))
        Next

      Catch ex As Exception : Throw
        
      Finally

      End Try
      Return dtReturn
    End Function

    Public Class TableParams
        Public ColumnName As String
        Public ColumnType As Type

        Public Sub New(ByVal ColumnName As String, ByVal ColumnType As Type)
            Me.ColumnName = ColumnName
            Me.ColumnType = ColumnType
        End Sub
    End Class

Use the above Function like this…

Dim TableParams As New List(Of TableParams)
TableParams.Add(New TableParams("id", Type.GetType("System.Int32")))
TableParams.Add(New TableParams("CompanyName", Type.GetType("System.String")))
       TableParams.Add(New TableParams("EMail", Type.GetType("System.String")))
TableParams.Add(New TableParams("FirstName", Type.GetType("System.String")))
TableParams.Add(New TableParams("Surname", Type.GetType("System.String")))

Dim dtInviteList As DataTable = Common.BuildDataTable("ContactDetails", TableParams)

No comments:

Post a Comment