HomeSearch

VB.NET DataColumn Class

Create, loop over and access a DataColumn, which is part of a DataTable.
DataColumn. A DataTable is represented by several types. In the table, a column represents the name and type of one cell in every row. This is called a DataColumn. And with the DataColumn class, we can add and loop over columns.DataTable
Example. Let's get started with this example program. In the first statements, it creates a new DataTable and adds three columns to it. Internally the DataTable actually creates DataColumn instances—but we do not see them here.

Next: We create a DataColumn object instance explicitly. We use the New DataColumn constructor.

Argument 1: This constructor receives two arguments. The first argument is the name of the column—a String.

Argument 2: The second argument is the type of the column. This is specified with the return value of GetType.

For-Each: In the For-Each loop, we use the Columns property on the DataTable. And we print the name and DataType for each column with Console.WriteLine.

For Each, ForConsole
VB.NET program that uses DataColumn Module Module1 Sub Main() ' Create DataTable and add columns. Dim table As DataTable = New DataTable() table.Columns.Add("Dosage", GetType(Integer)) table.Columns.Add("Medication", GetType(String)) table.Columns.Add("Patient", GetType(String)) ' Add a column object in a different way. Dim column As DataColumn = New DataColumn("Appointment", GetType(DateTime)) table.Columns.Add(column) ' Add some rows. table.Rows.Add(32, "Combivent", "Jane", DateTime.Now) table.Rows.Add(100, "Dilantin", "Mark", DateTime.Now) ' Loop over columns. For Each c As DataColumn In table.Columns Console.WriteLine("{0} = {1}", c, c.DataType) Next End Sub End Module Output Dosage = System.Int32 Medication = System.String Patient = System.String Appointment = System.DateTime
Indexer. Internally the DataTable type is implemented with Hashtable. This provides a fast way to access DataColumns by their names. This can be done with the indexer syntax. Try adding these two lines to the above program.

Result: The two statements return the first column in the DataTable—this is the Dosage column.

Hashtable: More information is available on the Hashtable type. This is an older but still efficient collection.

Hashtable
Statements that access DataColumns: VB.NET Console.WriteLine(table.Columns(0)) Console.WriteLine(table.Columns("Dosage"))
Summary. A DataColum is an essential part of a DataTable. For rows and data to be added to a DataTable, columns must first exist. And they must match the data added. This provides an important level of validation to the DataTable.DataRow

Review: Use DataColumns in a DataTable with the GetType argument to create typed, and validated, relational data in memory.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls