2.2. Creating a DataTable and Adding It to a DataSet

Problem

You need to create a table and add it to a DataSet.

Solution

Use the Add() or AddRange() method of the DataTableCollection of the DataSet, which is exposed through its Tables property.

The solution creates, configures, and adds a column to a DataTable using three different techniques:

  • Add a DataTable to a DataSet and configure the DataTable.

  • Creates and configures a DataTable and adds it to a DataSet.

  • Creates multiple DataTable objects, configures them, and adds them to the DataSet using the AddRange() method of the DataTableCollection of the DataSet.

The C# code in Program.cs in the project CreateDataTableAddDataSet is shown in Example 2-2.

Example 2-2. File: Program.cs for CreateDataTableAddDataSet solution

using System; using System.Data; namespace CreateDataTableAddDataSet { class Program { static void Main(string[] args) { DataSet ds = new DataSet(); // Add a DataTable named Table-1 directly DataTable dt1 = ds.Tables.Add("Table-1"); // ... Configure the DataTable -- add some columns, etc. // Add a DataTable named Table-2 by creating the table // and adding it to the DataSet DataTable dt2 = new DataTable("Table-2"); // ... Configure the DataTable -- add some columns, etc. ds.Tables.Add(dt2); // Add multiple DataTables to the DataSet DataTable dt3 = new DataTable("Table-3"); DataTable dt4 = new DataTable("Table-4"); // ... Configure the DataTable -- add some columns, etc. ds.Tables.AddRange(new DataTable[] { dt3, dt4 }); // Output ...

Get ADO.NET 3.5 Cookbook, 2nd Edition 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.