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.

Example

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.

DataSet customerOrders = new("CustomerOrders");

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

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

ordersTable.PrimaryKey = new DataColumn[] { pkOrderID };
Dim customerOrders As New DataSet("CustomerOrders")

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

Dim pkOrderID 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() {pkOrderID}

Case Sensitivity

Two or more tables or relations with the same name, but different casing, can exist in a DataSet. In such cases, references by name to tables and relations are case sensitive. For example, if the DataSet dataSet contains tables Table1 and table1, you would reference Table1 by name as dataSet.Tables["Table1"], and table1 as dataSet.Tables["table1"]. Attempting to reference either of the tables as dataSet.Tables["TABLE1"] would generate an exception.

The case-sensitivity behavior does not apply if only one table or relation has a particular name. For example, if the DataSet has only Table1, you can reference it using dataSet.Tables["TABLE1"].

Note

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.

Namespace Support

In versions of ADO.NET earlier than 2.0, two tables could not have the same name, even if they were in different namespaces. This limitation was removed in ADO.NET 2.0. A DataSet can contain two tables that have the same TableName property value but different Namespace property values.

See also