VB.NET DataTable Example

Dot Net Perls
The VB.NET programming language

You want to create a DataTable type instance in the VB.NET programming language, which enables you to collect information that can easily be stored to a database. The DataTable class can be instantiated just like any other collection; additionally, it has the Columns and Rows properties, which enable programmatic mutation of the storage.

Example

First, this is a simple example of how to create a DataTable type instance. The VB.NET program defines two routines: the Main entry point, and the GetTable function, which returns a new DataTable. When the GetTable function is invoked, it creates a new DataTable and adds four columns to it.

The columns are named with a string argument and a Type argument; they are of type Integer, String, String, and DateTime. In a DataTable, each column has a specific type of data it can contain. Finally, the GetTable method adds five rows to the DataTable; the arguments to the Rows.Add method are of the types specified in the columns.

Program that creates DataTable instance [VB.NET]

Module Module1

    Sub Main()
	' Get a DataTable instance from helper function.
	Dim table As DataTable = GetTable()
    End Sub

    ''' <summary>
    ''' Helper function that creates new DataTable.
    ''' </summary>
    Function GetTable() As DataTable
	' Create new DataTable instance.
	Dim table As New DataTable
	' Create four typed columns in the DataTable.
	table.Columns.Add("Dosage", GetType(Integer))
	table.Columns.Add("Drug", GetType(String))
	table.Columns.Add("Patient", GetType(String))
	table.Columns.Add("Date", GetType(DateTime))
	' Add five rows with those columns filled in the DataTable.
	table.Rows.Add(25, "Indocin", "David", DateTime.Now)
	table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now)
	table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now)
	table.Rows.Add(21, "Combivent", "Janet", DateTime.Now)
	table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now)
	Return table
    End Function

End Module
Question and answer

What happens next? This program text alone is not useful for creating a functional data-driven application. However, by using the general pattern of adding columns and rows, you can construct usable DataTables in any program context, and then do more useful tasks such as storing them to SQL Server databases, or displaying them on a DataGridView control in Windows Forms.

DataGridView Usage

Summary

In this short introductory article, we explored the DataTable type in the VB.NET programming language. Although the DataTable example shown here is not useful in a significant way on its own, this style of programmatic DataTable mutation is applicable to many VB.NET programs, including web applications using the ASP.NET framework; it simply describes the instructions that form an in-memory data representation object.

DataRow Tips VB.NET Tutorials