Reader Level:

How to Create a DataTable And Add it to a DataSet

By Mukesh Kumar on Jun 24, 2011
In this article we are going to see how to create a DataTable and add it to a DataSet

In this article we are going to see how to create a DataTable and add it to a DataSet.

Example :

using System;
using System.Data;

namespace CreateDataTable
static void Main(string[] args)
DataSet objDs = newDataSet();

// Add a DataTable to DataSet directly
DataTable objDt1 = objDs.Tables.Add("Table 1");
//  add some columns here

// Creating the table and adding it to the DataSet
DataTable objDt2 = newDataTable("Table 2");
//  add some columns here

// Add multiple DataTables to the DataSet
DataTable objDt3 = newDataTable("Table 3");
DataTable objDt4 = newDataTable("Table 4");
//  add some columns here
            objDs.Tables.AddRange(newDataTable[] { objDt3, objDt4 });

Console.WriteLine("DataSet has {0} DataTables \n", objDs.Tables.Count);
foreach (DataTable objDt in objDs.Tables)
Console.WriteLine("{0}", objDt.TableName);

Console.WriteLine("\nPress any key to continue.");

In this example we are using the Add() and AddRange() methods of the DataTableCollection of the DataSet to add a DataTable to a DataSet. Here are examples of three different techniques to add a DataTable to a DataSet.

  1. Add a DataTable directly to a DataSet

  2. Create a DataTable and Add it to a DataSet

  3. Create multiple DataTable objects and add them to DataSet using the AddRange() method of the DataTableCollection of the DataSet.

The DataTableCollection contains all of the DataTable objects for a particular DataSet. You can access the DataTableCollection of a DataSet using the Tables property.

The key methods of the DataTableCollection are Add(), AddRange(), AddRange(), Clear(), Contains(), CopyTo(), IndexOf(), Remove(), RemoveAt()

Add() method has four overloads:

  • Add()

  • Add(DataTable dataTable)

  • Add(string tableName)

  • Add(string tableName, string namespace)

Output :



Mukesh Kumar
Mukesh Kumar

I have over 7+ years of experience working with Microsoft technologies. I have earned my Microsoft Certified Technology Specialist (MCTS) certification. I'm a highly motivated self-starter with an aptitude for learning n... Read more



Spire.Doc - Free .NET Word API
Use Spire.Doc to create, read, write, print, and convert word documents to OpenXML, RTF, TXT, XPS, EPUB, EMF, HTML, Image and PDF.

Trending up

Infragistics jQuery Controls