DataColumn Class
This page was last reviewed on Sep 27, 2022.
Dot Net Perls
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 Module
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.
Result The 2 statements return the first column in the DataTable—this is the Dosage column.
Console.WriteLine(table.Columns(0)) Console.WriteLine(table.Columns("Dosage"))
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 27, 2022 (edit link).
© 2007-2024 Sam Allen.