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
Name | Type | Description |
---|---|---|
Columns | DataColumnCollection | Gets the collection that contains the columns of the table. |
Rows | DataRowCollection | Gets the collection that contains the rows of the table. |
TableName | string | The name of the table. |
PrimaryKey | DataColumn[] | An array of columns that function as primary keys for the table. |
Name | Signature | Description |
---|---|---|
AcceptChanges | void AcceptChanges() | Commits all the changes made to the table since it was loaded or since the last time AcceptChanges was called. |
Load | void Load(IDataReader) | Populates a DataTable with values from a data source using an IDataReader . |
NewRow | DataRow NewRow() | Creates a new DataRow with the same schema as the table. |
Name | Delegate | Description |
---|---|---|
RowChanging | DataRowChangeEventHandler | Occurs before a row changes. |
RowChanged | DataRowChangeEventHandler | Occurs after a row has changed. |
RowDeleting | DataRowChangeEventHandler | Occurs before a row is deleted. |
RowDeleted | DataRowChangeEventHandler | Occurs 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.