Adding a DataTable to a DataSet

ADO.NET enables you to create DataTable objects and add them to an existing DataSet. You can set constraint information for a DataTable by using the PrimaryKey and Unique properties of DataColumn objects, which are added to the Columns collection of the DataTable.

The following example constructs a DataSet, adds a new DataTable object to the DataSet, and then adds three DataColumn objects to the table. Finally, the code sets one column as the primary key column.

Dim custDS As DataSet = New DataSet("CustomerOrders")

Dim ordersTable As DataTable = custDS.Tables.Add("Orders")

Dim pkCol As DataColumn = ordersTable.Columns.Add("OrderID", Type.GetType("System.Int32"))
ordersTable.Columns.Add("OrderQuantity", Type.GetType("System.Int32"))
ordersTable.Columns.Add("CompanyName", Type.GetType("System.String"))

ordersTable.PrimaryKey = New DataColumn() {pkCol}
[C#]DataSet custDS = new DataSet("CustomerOrders");

DataTable ordersTable = custDS.Tables.Add("Orders");

DataColumn pkCol = ordersTable.Columns.Add("OrderID", typeof(Int32));
ordersTable.Columns.Add("OrderQuantity", typeof(Int32));
ordersTable.Columns.Add("CompanyName", typeof(string));

ordersTable.PrimaryKey = new DataColumn[] {pkCol};

Case Sensitivity

References by name to tables and relations in a DataSet are case-sensitive. Two or more tables or relations can exist in a DataSet that have the same name, but that differ in case. For example you can have Table1 and table1. In this situation, a reference to one of the tables by name must match the case of the table name exactly, otherwise an exception is thrown. For example, if the DataSet myDS contains tables Table1 and table1, you would reference Table1 by name as myDS.Tables["Table1"], and table1 as myDS.Tables ["table1"]. Attempting to reference either of the tables as myDS.Tables ["TABLE1"] would generate an exception.

The case-sensitivity rule does not apply if only one table or relation exists with a particular name. That is, if no other table or relation object in the DataSet matches the name of that particular table or relation object, even by a difference in case, you can reference the object by name using any case and no exception is thrown. For example, if the DataSet has only Table1, you can reference it using myDS.Tables["TABLE1"].

The CaseSensitive property of the DataSet does not affect this behavior. The CaseSensitive property applies to the data in the DataSet and affects sorting, searching, filtering, enforcing constraints, and so on. References to the tables or relations in a DataSet are not affected by the CaseSensitive property.

See Also

Creating and Using DataSets | DataSet Class | DataTable Class