C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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, ForConsoleVB.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
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.
HashtableStatements that access DataColumns: VB.NET
Console.WriteLine(table.Columns(0))
Console.WriteLine(table.Columns("Dosage"))
Review: Use DataColumns in a DataTable with the GetType argument to create typed, and validated, relational data in memory.