Name

Columns

Synopsis


DataColumnCollection dcc = DataTable.Columns;

Accesses the DataColumnCollection for the DataTable, providing access to the DataColumn objects belonging to the DataTable. The Columns property can be used to add, remove, and examine the DataColumn objects in a DataTable.

Examples

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, and so on, are assigned to the new column. The following examples show how to create a column using the Add( ) method:

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

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

dt.Columns.Add(col);

 

// adding and creating a column in the same statement

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

The second method is AddRange( ), 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 the array to the table

dt.Columns.AddRange(dca);

There are several properties and methods that can ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.