The DataTable contains a collection of DataColumn objects. This collection of columns defines the structure of the table. To add a new column to this collection, use the collection's Add method.
In the example below, we add three columns to a DataTable using the ColumnsCollection class's Add method; the method specifies the ColumnName and DataType properties.
[VB] Dim workTable as DataTable Dim workColumn as DataColumn WorkTable = new DataTable("Customers") workColumn = workTable.Columns.Add("CustID", System.Type.GetType("System.Int32") ) workColumn.AllowNull = false workColumn.Unique = true workColumn = workTable.Columns.Add("CustomerNameLast", System.Type.GetType("System.String") ) workColumn = workTable.Columns.Add("CustomerNameFirst", System.Type.GetType("System.String") ) workColumn = workTable.Columns.Add("Purchases", System.Type.GetType("System.Double") ) [C#] DataColumn workColumn = null; DataTable workTable = new DataTable("Customers"); workColumn = workTable.Columns.Add("CustID", System.Type.GetType("System.Int32") ); workColumn.AllowNull = false; workColumn.Unique = true; workColumn = workTable.Columns.Add("CustomerNameLast", System.Type.GetType("System.String") ); workColumn = workTable.Columns.Add("CustomerNameFirst", System.Type.GetType("System.String") ); workColumn = workTable.Columns.Add("Purchases", System.Type.GetType("System.Double") );
The first task is to declare a variable of type DataColumn named "workColumn." Using C#, the variable is initialized to null.
DataColumn workColumn = null;
Next, we declare an instance of the table to which we're going to add the new columns. We use the constructor to give the table the name "Customers" by which we will reference it later.
DataTable worktable = new DataTable("Customers");
Now we start the job of actually adding the new columns to the table. We'll actually add three columns: CustID (type: Int32), CustomerNameLast (type: String), and CustomerNameFirst (type: String).
workColumn = workTable.Columns.Add("CustID", System.Type.GetType("System.Int32") );
When the data type is assigned to the column, we're use a NGWS frameworks data type - not an OLE DB or database specific data type. To set the type, use the System function – System.Type.GetType
- that returns a type name for the actual data type that we want.
System.Type.GetType("System.Int32")
The GetType method returns a null if the type specified could not be loaded.
The ColumnsCollection on the DataTable provides has two overloads of the Add method:
Public DataColumn Add(String columnname, Type type) Public DataColumn Add(String columnname)