Create Custom DataTable

Datatables are very useful containers for data and have a very familiar format for database programmers. The most common method for creating them is using a DataAdapter. When using a DataAdapter, you are obliged to use the data schema of the query used to fill the datatable. Here is a method in VB.NET for creating a datatable with exactly the columns and attributes called for in your program.


Private Function CreateOrdersTable() As DataTable
Dim strErrorMessage As String
Dim intExitCode As Integer
Try
Dim OrdersTable As DataTable
OrdersTable = New DataTable(“Orders”)

Dim Cost As DataColumn = New DataColumn
Cost.ColumnName = “Cost”
Cost.DataType = System.Type.GetType(“System.Decimal”)
OrdersTable.Columns.Add(Cost)

Dim Package As DataColumn = New DataColumn
Package.ColumnName = “Package”
Package.DataType = System.Type.GetType(“System.String”)
OrdersTable.Columns.Add(Package)

Dim CustomerID As DataColumn = New DataColumn
CustomerID.ColumnName = “CustomerID”
CustomerID.DataType = System.Type.GetType(“System.Int32”)
OrdersTable.Columns.Add(CustomerID)

Dim AccountDate As DataColumn = New DataColumn
AccountDate.ColumnName = “AccountDate”
AccountDate.DataType = System.Type.GetType(“System.DateTime”)
OrdersTable.Columns.Add(AccountDate)

CreateOrdersTable = OrdersTable

Catch ex As Exception
strErrorMessage = ex.Message
intExitCode = Err.Number()
Finally
If intExitCode <> 0 Then
MsgBox(“Error ” & intExitCode & ” occurred. ” & strErrorMessage, MsgBoxStyle.OKOnly + MsgBoxStyle.Critical)
End If
End Try

End Function

About the author

Leave a Reply

Your email address will not be published. Required fields are marked *