# Adding Columns to a DataTable

A DataTable contains a collection of DataColumn objects referenced by the Columns property of the table. This collection of columns, along with any constraints, defines the schema, or structure, of the table.

You create DataColumn objects within a table by using the DataColumn constructor, or by calling the Add method of the Columns property of the table, which is a DataColumnCollection. The Add method accepts optional ColumnName, DataType, and Expression arguments and creates a new DataColumn as a member of the collection. It also accepts an existing DataColumn object and adds it to the collection, and returns a reference to the added DataColumn if requested. Because DataTable objects are not specific to any data source, .NET Framework types are used when specifying the data type of a DataColumn.

The following example adds four columns to a DataTable.

Dim workTable As DataTable = New DataTable("Customers")

Dim workCol As DataColumn = workTable.Columns.Add( _
"CustID", Type.GetType("System.Int32"))
workCol.AllowDBNull = false
workCol.Unique = true


DataTable workTable = new DataTable("Customers");

workCol.AllowDBNull = false;
workCol.Unique = true;


If you are using XElement as the DataType of a DataColumn in the DataTable, XML serialization will not work when you read in data. For example, if you write out a XmlDocument by using the DataTable.WriteXml method, upon serialization to XML there is an additional parent node in the XElement. To work around this problem, use the SqlXml type instead of XElement. ReadXml and WriteXml work correctly with SqlXml.