Working with Tables in the DataSet
Tables belonging to the
DataSet are stored as DataTable
objects in a
DataTableCollection
object and accessed through the
Tables
property of the
DataSet. This section examines some methods and
properties of the DataTableCollection.
Tables are added to the DataSet using the
Add( )
method of the
DataTableCollection. The Add( )
method takes an optional table name argument. If this argument
isn’t supplied, the tables are automatically named
Table, Table1, 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);The AddRange( )
method allows more than one table to
be added to the DataSet in the same statement. The
method takes an array of DataTable objects as the
argument, as the following example shows:
// create two new tables
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
// use the AddRange() method to add them to the DataSet.
ds.Tables.AddRange(new DataTable[] {dt1, dt2});A DataTable can also be created automatically in a
DataSet when the Fill( )
or FillSchema( )
method of the
DataAdapter is called. A new table is created and
filled with the data or schema, respectively, from the data source,
as illustrated in the following code:
// connection and select command strings String connString = "Data Source=(local);Integrated security=SSPI;" + "Initial Catalog=Northwind;"; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access