Name

Tables

Synopsis


DataTableCollection dtc = DataSet.Tables;

Accesses the DataTableCollection contained by the DataSet that contains the DataTable objects belonging to the DataSet.

Example

The DataTableCollection has two methods that can add a table to a DataSet. The Add( ) method takes an optional table name argument and is used to add tables to the DataTableCollection. If this argument isn’t supplied, the tables are automatically named Table, Table1, Table2, and so on. The following example adds a table to a DataSet:

DataSet ds = new DataSet("MyDataSet");

DataTable dt = new DataTable("MyTable");



// ... code to define the schema for the newly constructed DataTable



ds.Tables.Add(dt);

Alternatively, a DataTable can first be constructed within the DataTablesCollection and subsequently have its schema defined:

DataSet ds = new DataSet("MyDataSet");

DataTable dt = ds.Tables.Add("MyTable");



// ... code to define the schema for newly constructed DataTable

A reference to the table that already exists within the DataSet can be retrieved. Most commonly, this is done using the table name or the table ordinal as shown in these examples:

// using the table name

DataTable dt = ds.Tables("MyTable");



// using the table ordinal

DataTable dt = ds.Tables[0];

The Count property returns the number of tables in the DataSet, as shown here:

Int32 tableCount = ds.Tables.Count;

The Contains( ) method returns whether a specific DataTable exists within a DataSet, as shown next:

bool tableExists = ds.Tables.Contains("MyTable"); ...

Get ADO.NET in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.