Working with Columns

The schema for a table is defined by the columns in the table and the constraints on those columns. Columns belonging to the DataTable are stored as DataColumn objects in a DataColumnCollection object and are accessed through the Columns property of the DataTable. This section examines some methods and properties of the DataColumnCollection.

There are two methods that can add a column to a table. The Add( ) method optionally takes arguments that specify the name, type, and expression of the column to be added. An existing column can be added by passing a reference to an existing column. If no arguments are passed, the default names Column1, Column2, Column3, and so on are assigned to the new columns. The following examples show how to create columns within the table:

// adding a column using a reference to an existing column

DataColumn col = new DataColumn("MyColumn, typeof(System.Int32));



// adding and creating a column in the same statement

dt.Columns.Add("MyColumn", typeof(System.Int32));

The second method for adding columns is the AddRange( ) method, which allows more than one column stored in a DataColumn array to be added to the table in a single statement, as shown in the following example:

DataTable dt = new DataTable("MyTable"); // create and add two columns to the DataColumn array DataColumn[] dca = new DataColumn[] {new DataColumn("Col1", typeof(System.Int32)), new DataColumn("Col2", typeof(System.Int32))}; // add the columns in ...

Get ADO.NET in a Nutshell now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.