Create And Use A DataTable In C#

C# DataTable class represents a data table in C#. Code sample in this article demonstrates how to create a DataTable dynamically in C# code and DataTable rows and DataTable columns and display data in a DataGridView control using DataGridView.DataSource data binding.

The DataTable class in C# ADO.NET is a database table representation and provides a collection of columns and rows to store data in a grid form. The code sample in this artilce explains how to create a DataTable at run-time in C#. You will also learn how to create a DataTable columns and rows, add data to a DataTable and bind a DataTable to a DataGridView control using data binding.

Table 1 describes some of the common DataTable properties.

Table 1: The Data Table class properties

PROPERTY DESCRIPTION
Columns Represents all table columns
Constraints Represents all table constraints
DataSet Returns the dataset for the table
DefaultView Customized view of the data table
ChildRelation Return child relations for the data table
ParentRelation Returns parent relations for the data table
PrimaryKey Represents an array of columns that function as primary key for the table
Rows All rows of the data table
TableName Name of the table

Table 2 describes some of the common DataTable methods.
 
Table 2: The Data Table Class Methods

METHOD DESCRIPTION
AcceptChanges Commits all the changes made since last AcceptChanges was called
Clear Deletes all data table data
Clone Creates a clone of a DataTable including its schema
Copy Copies a data table including its schema
NewRow Creates a new row, which is later added by calling the Rows.Add method
RejectChanges Reject all changed made after last AcceptChanges was called
Reset Resets a data table's original state
Select Gets an array of rows based on the criteria

The DataTable class provides methods and properties to remove, copy, and clone data tables. You can also apply filters and sorting on a DataTable. The Constraints property provides access to all the constraints that a data table has. You can also access the child and parent relationship using ChildRelation and ParentRelation objects.

In this code, I'll create two DataTable objects, Customers and Orders, and set a relationship between them. After that, I will add data to the DataTables and bind a DataTable to a DataGridView control to load and display data in the control.
 
Steps:  
 
Open Visual Studio 2017 or later version and create a Windows Forms applciation using C#. 
 
Add a DataGridView control to the Form and resize your control as you see it fits.
 
Now, on the Form's constructor, call the following three methods, CreateCustomersTable(), CreateOrdersTable(), and BindData() methods after InitializeComponent() method.
 
The form constructor looks like listing 1.

Listing 1: Form's constructor calling CreateCustomers Table CreateOrdersTable, and BindData
  1. public Form1()  
  2. {  
  3.     InitializeComponent();  
  4.     CreateCustomersTable();  
  5.     CreateOrdersTable();  
  6.     BindData();  
  7. }  
You also need to add a DataSet variable, dtSet, in the beginning of your form. See the following code
  1. public class Form1 : System.Windows.Forms.Form  
  2. {   
  3.     private DataSet dtSet;  
  4. }  
In listing 2, the CreateCustomersTable method creates the Customers data table with id, Name, and Address columns and adds three data rows to it. The Create OrdersTable method creates the Orders table with order Id, cust Id, Name, and Description columns and adds data it. The BindData method creates a customer/ orders relationship and binds the data to a DataGrid control using DataSet. 

Listing 2 shows All Three CreateCustomerTable, CreateOrderTable, and BindData methods.

Listing 2: Customer/orders relationship example 
  1. // Create Customers table   
  2. private void CreateCustomersTable()  
  3. {  
  4.     // Create a new DataTable.    
  5.     DataTable custTable = new DataTable("Customers");  
  6.     DataColumn dtColumn;  
  7.     DataRow myDataRow;  
  8.   
  9.     // Create id column  
  10.     dtColumn = new DataColumn();  
  11.     dtColumn.DataType = typeof(Int32);  
  12.     dtColumn.ColumnName = "id";  
  13.     dtColumn.Caption = "Cust ID";  
  14.     dtColumn.ReadOnly = false;  
  15.     dtColumn.Unique = true;  
  16.     // Add column to the DataColumnCollection.  
  17.     custTable.Columns.Add(dtColumn);  
  18.   
  19.     // Create Name column.    
  20.     dtColumn = new DataColumn();  
  21.     dtColumn.DataType = typeof(String);  
  22.     dtColumn.ColumnName = "Name";  
  23.     dtColumn.Caption = "Cust Name";  
  24.     dtColumn.AutoIncrement = false;  
  25.     dtColumn.ReadOnly = false;  
  26.     dtColumn.Unique = false;  
  27.     /// Add column to the DataColumnCollection.  
  28.     custTable.Columns.Add(dtColumn);  
  29.   
  30.     // Create Address column.    
  31.     dtColumn = new DataColumn();  
  32.     dtColumn.DataType = typeof(String);  
  33.     dtColumn.ColumnName = "Address";  
  34.     dtColumn.Caption = "Address";  
  35.     dtColumn.ReadOnly = false;  
  36.     dtColumn.Unique = false;  
  37.     // Add column to the DataColumnCollection.    
  38.     custTable.Columns.Add(dtColumn);  
  39.   
  40.     // Make id column the primary key column.    
  41.     DataColumn[] PrimaryKeyColumns = new DataColumn[1];  
  42.     PrimaryKeyColumns[0] = custTable.Columns["id"];  
  43.     custTable.PrimaryKey = PrimaryKeyColumns;  
  44.   
  45.     // Create a new DataSet  
  46.     dtSet = new DataSet();  
  47.   
  48.     // Add custTable to the DataSet.    
  49.     dtSet.Tables.Add(custTable);  
  50.   
  51.     // Add data rows to the custTable using NewRow method    
  52.     // I add three customers with their addresses, names and ids   
  53.     myDataRow = custTable.NewRow();  
  54.     myDataRow["id"] = 1001;  
  55.     myDataRow["Address"] = "43 Lanewood Road, cito, CA";  
  56.     myDataRow["Name"] = "George Bishop";  
  57.     custTable.Rows.Add(myDataRow);  
  58.     myDataRow = custTable.NewRow();  
  59.     myDataRow["id"] = 1002;  
  60.     myDataRow["name"] = "Rock joe";  
  61.     myDataRow["Address"] = " kind of Prussia, PA";  
  62.     custTable.Rows.Add(myDataRow);  
  63.     myDataRow = custTable.NewRow();  
  64.     myDataRow["id"] = 1003;  
  65.     myDataRow["Name"] = "Miranda";  
  66.     myDataRow["Address"] = "279 P. Avenue, Bridgetown, PA";  
  67.     custTable.Rows.Add(myDataRow);  
  68. }  
  69.   
  70. // Create Orders table  
  71. private void CreateOrdersTable()  
  72. {  
  73.     // Create a DataTable  
  74.     DataTable ordersTable = new DataTable("Orders");  
  75.     DataColumn dtColumn;  
  76.     DataRow dtRow;  
  77.   
  78.     // Create OrderId column    
  79.     dtColumn = new DataColumn();  
  80.     dtColumn.DataType = Type.GetType("System.Int32");  
  81.     dtColumn.ColumnName = "OrderId";  
  82.     dtColumn.AutoIncrement = true;  
  83.     dtColumn.Caption = "Order ID";  
  84.     dtColumn.ReadOnly = true;  
  85.     dtColumn.Unique = true;  
  86.     ordersTable.Columns.Add(dtColumn);  
  87.   
  88.     // Create Name column.    
  89.     dtColumn = new DataColumn();  
  90.     dtColumn.DataType = Type.GetType("System.String");  
  91.     dtColumn.ColumnName = "Name";  
  92.     dtColumn.Caption = "Item Name";  
  93.     ordersTable.Columns.Add(dtColumn);  
  94.   
  95.     // Create CustId column which Reprence Cust Id from    
  96.     // The cust Table    
  97.     dtColumn = new DataColumn();  
  98.     dtColumn.DataType = Type.GetType("System.Int32");  
  99.     dtColumn.ColumnName = "CustId";  
  100.     dtColumn.AutoIncrement = false;  
  101.     dtColumn.Caption = "CustId";  
  102.     dtColumn.ReadOnly = false;  
  103.     dtColumn.Unique = false;  
  104.     ordersTable.Columns.Add(dtColumn);  
  105.   
  106.     // Create Description column.    
  107.     dtColumn = new DataColumn();  
  108.     dtColumn.DataType = Type.GetType("System.String");  
  109.     dtColumn.ColumnName = "Description";  
  110.     dtColumn.Caption = "DescriptionName";  
  111.     ordersTable.Columns.Add(dtColumn);  
  112.   
  113.     // Add ordersTable to DataSet    
  114.     dtSet.Tables.Add(ordersTable);  
  115.   
  116.     // ADD two rows to the customer Id 1001    
  117.     dtRow = ordersTable.NewRow();  
  118.     dtRow["OrderId"] = 0;  
  119.     dtRow["Name"] = "ASP Book";  
  120.     dtRow["custId"] = 1001;  
  121.     dtRow["Description"] = "Same Day";  
  122.     ordersTable.Rows.Add(dtRow);  
  123.     dtRow = ordersTable.NewRow();  
  124.     dtRow["OrderId"] = 1;  
  125.     dtRow["Name"] = " C# Book";  
  126.     dtRow["custId"] = 1001;  
  127.     dtRow["description"] = "2 DAY AIR";  
  128.     ordersTable.Rows.Add(dtRow);  
  129.     // Add two rows to Customer id 1002    
  130.     dtRow = ordersTable.NewRow();  
  131.     dtRow["OrderId"] = 2;  
  132.     dtRow["Name"] = "Data Quest";  
  133.     dtRow["Description"] = "Monthly magazine";  
  134.     dtRow["CustId"] = 1002;  
  135.     ordersTable.Rows.Add(dtRow);  
  136.     dtRow = ordersTable.NewRow();  
  137.     dtRow["OrderId"] = 3;  
  138.     dtRow["Name"] = "PC Magazine";  
  139.     dtRow["Description"] = "Monthly Magazine";  
  140.     dtRow["CustId"] = 1003;  
  141.     ordersTable.Rows.Add(dtRow);  
  142.     // Add two rows to Customer id 1003    
  143.     dtRow = ordersTable.NewRow();  
  144.     dtRow["OrderId"] = 4;  
  145.     dtRow["Name"] = "PCMagazine";  
  146.     dtRow["Description"] = "Monthly Magazine";  
  147.     dtRow["custId"] = 1003;  
  148.     ordersTable.Rows.Add(dtRow);  
  149.     dtRow = ordersTable.NewRow();  
  150.     dtRow["OrderId"] = 5;  
  151.     dtRow["Name"] = "C# Book";  
  152.     dtRow["CustId"] = 1003;  
  153.     dtRow["Description"] = "2 Day Air ";  
  154.     ordersTable.Rows.Add(dtRow);  
  155. }  
  156.   
  157. // This method creates a customer order relationship and data tables    
  158. // Also displays Customers table data in a DataGridView control  
  159. private void BindData()  
  160. {  
  161.     DataRelation dtRelation;  
  162.     DataColumn custCol = dtSet.Tables["Customers"].Columns["id"];  
  163.     DataColumn orderCol = dtSet.Tables["orders"].Columns["custId"];  
  164.     dtRelation = new DataRelation("CustOrderRelation ", custCol, orderCol);  
  165.     dtSet.Tables["orders"].ParentRelations.Add(dtRelation);  
  166.   
  167.     // Create a BindingSource  
  168.     BindingSource bs = new BindingSource();  
  169.     bs.DataSource = dtSet.Tables["Customers"];  
  170.   
  171.     // Bind data to DataGridView.DataSource  
  172.     dataGridView1.DataSource = bs;              
  173. }  
As you can see from the CreateCustomersTable method in listing 2, it creates the Customers table using DataTable and adds id, Name and Address columns to the table. You use DataColumn to add these columns. The id column has properties such as ReadOnly and Unique. As discussed earlier, to add a column to a DataTable, you create a DataColumn object, set its properties, and then call the DataTable.Columns.Add method. Similar to the id column, you add two more columns, Name and Address, of string type to the table. After that, you make the id column the primary key by the setting DataTable.PrimaryKey as the id column: 
  1. PrimaryKeyColumns[0] = custTable.Columns["id"];  
  2. custTable.PrimaryKey = PrimaryKeyColumns;  
After creating a DataTable you add it to a DataSet using the DataSet.Tables.Add method. This method takes one argument of type DataTable:
  1. dtSet = new DataSet("customers");  
  2. dtSet.Tables.Add(custTable);  
Now, the last step is to add data to DataTable. You add data using DataRow.
 
First, you create a DataRow object using DataTable's NewRow method, add data to a DataRow's items, and add DataRow to the DataTable using the DataTable.Rows.Add method you'll follow the same method for the second table in createOrdersTable to create the orders table. The orders table has the fields OrderId, Name, Description, and custId.
 
The BindData method creates a relationship by using DataRelation and binds the id column of the Customers tables to the custId column of the Orders table. The name of the relationship is CustOrderRelation. After that you bind DataTable to the DataGrid using the SetDataBinding method.
 
Conclusion

This article originally written in 2001 from my ADO.NET book explains how to use a DataTable class of ADO.NET using C#.