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.
Class use. We use DataColumns in a DataTable with the GetType argument to create typed, and validated, relational data in memory. We can add and loop over columns.
Example. In the first statements, we create a DataTable and adds 3 columns to it. Internally the DataTable 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.
Detail In the For-Each loop, we use the Columns property on the DataTable. And we print the name and DataType for each column.
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 ModuleDosage = 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.
A 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 27, 2022 (edit link).