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
.
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.
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.
DataColumn
object instance explicitly. We use the New DataColumn
constructor.String
.GetType
.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
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.
DataTable
—this is the Dosage column.Console.WriteLine(table.Columns(0)) Console.WriteLine(table.Columns("Dosage"))
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.