Creating a DataTable
A DataTable, which represents one table of in-memory relational data, can be created and used independently, or can be used by other .NET Framework objects, most commonly as a member of a DataSet.
You can create a DataTable object by using the DataTable constructor, or by passing constructor arguments to the Add method of the Tables property of the DataSet, which is a DataTableCollection.
You can also create DataTable objects within a DataSet by using the Fill or FillSchema methods of the DataAdapter object, or from a pre-defined or inferred XML schema using the ReadXml, ReadXmlSchema, or InferXmlSchema methods of the DataSet. Note that after you have added a DataTable as a member of the Tables collection of one DataSet, you cannot add it to the collection of tables of any other DataSet.
When you first create a DataTable, it does not have a schema (a structure). To define the schema of the table, you must create and add DataColumn objects to the Columns collection of the table. You can also define a primary key column for the table, and create and add Constraint objects to the Constraints collection of the table. After you have defined the schema for a DataTable, you can add rows of data to the table by adding DataRow objects to the Rows collection of the table.
You are not required to supply a value for the TableName property when you create a DataTable; you can specify the property at another time, or you can leave it empty. However, when you add a table without a TableName value to a DataSet, the table will be given an incremental default name of TableN, starting with "Table" for Table0.
Note It is recommended that you avoid the naming convention of "Table" or "TableN" when you supply a TableName value, because the name you supply may conflict with an existing default table name in the DataSet. If the supplied name already exists, an exception will be thrown.
The following example creates an instance of a DataTable object and assigns it the name "Customers".
Dim workTable as DataTable = New DataTable("Customers") [C#] DataTable workTable = new DataTable("Customers");
The following example creates an instance of a DataTable by adding it to the Tables collection of a DataSet.
Dim custDS As DataSet = New DataSet Dim custTable As DataTable = custDS.Tables.Add("CustTable") [C#] DataSet custDS = new DataSet(); DataTable custTable = custDS.Tables.Add("CustTable");