Creating DataColumns

When creating a new DataColumn , the overloaded constructor allows up to four optional arguments to be specified to initialize the ColumnName, DataType, Expression, and ColumnMapping properties. The following example creates a column and specifies both its name and data type:

// create the column and set the name and data type using properties 

DataColumn col = new DataColumn();

col.ColumnName = "MyTextColumn";

col.DataType = typeof(System.String);



// the code below is identical to the above three lines

DataColumn col = new DataColumn("MyTextColumn", typeof(System.String));



// set the maximum length in characters of the new column

col.MaxLength = 50;

The following example demonstrates another overloaded constructor and subsequently sets some properties of the column:

// create another column

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

col.AllowDBNull = false;   // the column doesn't allow null values

col.DefaultValue = -1;     // set the default value

col.Caption = "ID #";      // column title used by certain bound controls

col.Unique = true;         // the column value is each row must be unique

col.ReadOnly = true;       // the column value cannot be changed once the

                           // the row is added to a table

If the column name isn’t supplied, the names Column1, Column2, Column3, and so on, are assigned when the column is added to the table. An exception is raised if the name of the column being added to the table is the same as the name of an existing column in the table.

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.