DataTable In C#

In the previous article, ADO.NET DataSet, we saw how to create and use a DataSet in C#. A DataSet may contain one or more DataTable objects. The C# DataTable class represents a data table. A DataTable can be used via the DataSet object as well as independently it's own.

A DataTable consists of Columns, Rows, and a Constraints collection.

A DataColumn defines the column name and datatype. We can create a new DataColumn using the DataColumn constructor or by invoking the Add method of the DataTable.Columns collection property. The DataColumn is the fundamental building block for creating the schema of a DataTable. We build the schema by adding one or more DataColumn objects to the DataColumnCollection. For more information, see Adding Columns to a Table. Each DataColumn has a DataType property that determines the kind of data the DataColumn contains. For example, we can restrict the data type to integers, or strings, or decimals. Because data contained by the DataTable is usually merged back into its original data source, we must match the data types to those in the data source.

  1. DataColumn FirstColumn == new DataColumn("ISBN", Type.GetType("System.Int32");  

Properties are such as AllowDBNull, Unique, and ReadOnly place restrictions on the entry and updating of data, thereby helping to ensure data integrity. We can also use the AutoIncrement, AutoIncrementSeed, and AutoIncrementStep properties to control automatic data generation. For more information about AutoIncrement columns, see Creating AutoIncrement Columns. For more information, see Defining a Primary Key for a Table. We can also ensure that values in a DataColumn are unique by creating a UniqueConstraint and adding it to the ConstraintCollection of the DataTable to which the DataColumn belongs. For more information, see Adding Constraints to a Table.

To create a relation between DataColumn objects, create a DataRelation object, and add it to the DataRelationCollection of a DataSet. We can use the Expression property of the DataColumn object to calculate the values in a column or create an aggregate column.

  1. private void MakeTable(DataTable firstTable) {    
  2.     // Create a DataTable. DataTable firstTable = new DataTable("firstTable");    
  3.     // Create a DataColumn and set various properties.     
  4.     DataColumn firstColumn = new DataColumn();    
  5.     firstColumn.DataType = System.Type.GetType("System.Decimal");    
  6.     firstColumn.AllowDBNull = false;    
  7.     firstColumn.Caption = "Price";    
  8.     firstColumn.ColumnName = "Price";    
  9.     firstColumn.DefaultValue = 25;    
  10.     // Add the column to the table.     
  11.     firstTable.Columns.Add(firstColumn);    
  12.     // Add 10 rows and set values.     
  13.     DataRow firstRow;    
  14.     for (int i = 0; i < 10; i++) {    
  15.         firstRow = firstTable.NewRow();    
  16.         firstRow["Price"] = i + 1;    
  17.         // Be sure to add the new row to the DataRowCollection.     
  18.         firstTable.Rows.Add(firstRow);    
  19.     }    
  20. }  

    The DataRow and DataColumn objects are primary components of a DataTable. Use the DataRow object and its properties and methods to retrieve and evaluate; and insert, delete, and update the values in the DataTable. The DataRowCollection represents the actual DataRow objects in the DataTable, and the DataColumnCollection contains the DataColumn objects that describe the schema of the DataTable. Use the overloaded Item property to return or sets the value of a DataColumn. Use the HasVersion and IsNull properties to determine the status of a particular row value, and the RowState property to determine the state of the row in relation to its parent DataTable.

    To create a new DataRow, use the NewRow method of the DataTable object. After creating a new DataRow, use the Add method to add the new DataRow to the DataRowCollection. Finally, call the AcceptChanges method of the DataTable object to confirm the addition. For more information about adding data to a DataTable, see Adding Data to a Table. We can delete a DataRow from the DataRowCollection by calling the Remove method of the DataRowCollection, or by calling the Delete method of the DataRow object. The Remove removes the row from the collection. In contrast, Delete marks the DataRow for removal. The actual removal occurs when we call AcceptChanges method. By calling Delete, we can programmatically check which rows are marked for removal before actually deleting them.

    1. private void CreateNewDataRow() {    
    2.     // Use the MakeTable function below to create a new table.    
    3.     DataTable firstTable;    
    4.     firstTable = MakeNamesTable();    
    5.     // Once a table has been created, use the NewRow to create a DataRow.    
    6.     DataRow firstRow;    
    7.     firstRow = firstTable.NewRow();    
    8.     // Then add the new row to the collection.    
    9.     firstRow["FirstName"] = "John";    
    10.     firstRow["LastName"] = "Smith";    
    11.     firstTable.Rows.Add(firstRow);    
    12.     foreach(DataColumn dc in firstTable.Columns)    
    13.     Console.WriteLine(dc.ColumnName);    
    14.     dataGrid1.DataSource = firstTable;    
    15. }    
    16. private DataTable MakeNamesTable() {    
    17.     // Create a new DataTable titled 'Names.'    
    18.     DataTable namesTable = new DataTable("Names");    
    19.     // Add three column objects to the table.    
    20.     DataColumn idColumn = new DataColumn();    
    21.     idColumn.DataType = System.Type.GetType("System.Int32");    
    22.     idColumn.ColumnName = "id";    
    23.     idColumn.AutoIncrement = true;    
    24.     namesTable.Columns.Add(idColumn);    
    25.     DataColumn FirstNameColumn = new DataColumn();    
    26.     FirstNameColumn.DataType = System.Type.GetType("System.String");    
    27.     FirstNameColumn.ColumnName = "FirstName";    
    28.     FirstNameColumn.DefaultValue = "FirstName";    
    29.     namesTable.Columns.Add(FirstNameColumn);    
    30.     DataColumn LastNameColumn = new DataColumn();    
    31.     LastNameColumn.DataType = System.Type.GetType("System.String");    
    32.     LastNameColumn.ColumnName = "LastName";    
    33.     namesTable.Columns.Add(LastNameColumn);    
    34.     // Create an array for DataColumn objects.    
    35.     DataColumn[] keys = new DataColumn[1];    
    36.     keys[0] = idColumn;    
    37.     namesTable.PrimaryKey = keys;    
    38.     // Return the new DataTable.    
    39.     return namesTable;    
    40. }  

      Relational databases enforce data integrity with constraints or rules applied to a column that defines what action to take when data in a related column or row is changed. In ADO.NET there are two types of constraints; ForeignKeyConstraint and UniqueConstraint. A constraint is a rule used to maintain the integrity of the data in the DataTable. For example, when we delete a value that is used in one or more related tables, a ForeignKeyConstraint determines whether the values in the related tables are also deleted, set to null values, set to default values, or whether no action occurs. A UniqueConstraint, on the other hand, simply ensures that all values within a particular table are unique. A base Constraint constructor is not used. Primary or unique key constraints are created using the UniqueConstraint constructor, and foreign key constraints are created using the ForeignKeyConstraint constructor.
      1. private void GetConstraints(DataTable firstTable) {    
      2.     Console.WriteLine();    
      3.     // Print the table's name.    
      4.     Console.WriteLine("TableName: " + firstTable.TableName);    
      5.     // Iterate through the collection and print each name and type value.    
      6.     foreach(Constraint cs in firstTable.Constraints) {    
      7.         Console.WriteLine("Constraint Name: " + cs.ConstraintName);    
      8.         Console.WriteLine("Type: " + cs.GetType().ToString());    
      9.         // If the constraint is a UniqueConstraint, print its properties using    
      10.         // a function below.    
      11.         if (cs is UniqueConstraint) {    
      12.             PrintUniqueConstraintProperties(cs);    
      13.         }    
      14.         // If the constraint is a ForeignKeyConstraint, print its properties    
      15.         // using a function below.    
      16.         if (cs is ForeignKeyConstraint) {    
      17.             PrintForeigKeyConstraintProperties(cs);    
      18.         }    
      19.     }    
      20. }    
      21. private void PrintUniqueConstraintProperties(Constraint cs) {    
      22.     UniqueConstraint uCS;    
      23.     uCS = (UniqueConstraint) cs;    
      24.     // Get the Columns as an array.    
      25.     DataColumn[] colArray;    
      26.     colArray = uCS.Columns;    
      27.     // Print each column's name.    
      28.     for (int i = 0; i < colArray.Length; i++) {    
      29.         Console.WriteLine("Column Name: " + colArray[i].ColumnName);    
      30.     }    
      31. }    
      32. private void PrintForeigKeyConstraintProperties(Constraint cs) {    
      33.     ForeignKeyConstraint fkeyCS;    
      34.     fkeyCS = (ForeignKeyConstraint) cs;    
      35.     // Get the Columns as an array.    
      36.     DataColumn[] colArray;    
      37.     colArray = fkeyCS.Columns;    
      38.     // Print each column's name.    
      39.     for (int i = 0; i < colArray.Length; i++) {    
      40.         Console.WriteLine("Column Name: " + colArray[i].ColumnName);    
      41.     }    
      42.     Console.WriteLine();    
      43.     // Get the related columns and print each column name.    
      44.     colArray = fkeyCS.RelatedColumns;    
      45.     for (int i = 0; i < colArray.Length; i++) {    
      46.         Console.WriteLine("Related Column Name: " + colArray[i].ColumnName);    
      47.     }    
      48.     Console.WriteLine();    
      49. }   

        Here is one more detailed article: ADO.NET DataTable Tutorial.