MSDN

System.Data.DataTable Class

Summary

The DataTable class represents an in-memory table of data. It provides methods for creating, accessing, and managing columns, rows, constraints, and relationships.

Syntax

public sealed class DataTable : MarshalByValueComponent, IListSource, ISupportInitialize, ISerializable, IXmlSerializable

Members

Properties
Methods
Events
NameTypeDescription
ColumnsDataColumnCollectionGets the collection that contains the columns of the table.
RowsDataRowCollectionGets the collection that contains the rows of the table.
TableNamestringThe name of the table.
PrimaryKeyDataColumn[]An array of columns that function as primary keys for the table.
NameSignatureDescription
AcceptChangesvoid AcceptChanges()Commits all the changes made to the table since it was loaded or since the last time AcceptChanges was called.
Loadvoid Load(IDataReader)Populates a DataTable with values from a data source using an IDataReader.
NewRowDataRow NewRow()Creates a new DataRow with the same schema as the table.
NameDelegateDescription
RowChangingDataRowChangeEventHandlerOccurs before a row changes.
RowChangedDataRowChangeEventHandlerOccurs after a row has changed.
RowDeletingDataRowChangeEventHandlerOccurs before a row is deleted.
RowDeletedDataRowChangeEventHandlerOccurs after a row has been deleted.

Example

using System;
using System.Data;

class Program
{
    static void Main()
    {
        // Create a new DataTable.
        DataTable table = new DataTable("Employees");

        // Add columns.
        table.Columns.Add("Id", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("HireDate", typeof(DateTime));

        // Define a primary key.
        table.PrimaryKey = new DataColumn[] { table.Columns["Id"] };

        // Add rows.
        table.Rows.Add(1, "Alice", DateTime.Parse("2020-01-15"));
        table.Rows.Add(2, "Bob", DateTime.Parse("2021-06-30"));

        // Display the data.
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine($"{row["Id"]}: {row["Name"]} (Hired {row["HireDate"]:d})");
        }
    }
}

Remarks

The DataTable class is a central component of ADO.NET and can be used both with disconnected data patterns as well as in conjunction with DataSet. It supports constraints, relationships, and data-binding to UI controls.