DataTable Class
The System.Data.DataTable
class represents an in‑memory table of data. It is part of the System.Data namespace and is used extensively with DataSet
, DataAdapter
, and other ADO.NET components.
Namespace
System.Data
Assembly
System.Data.dll
Key Properties
Name | Type | Description |
---|---|---|
TableName | string | Gets or sets the name of the table. |
Columns | DataColumnCollection | Collection of columns that define the schema. |
Rows | DataRowCollection | Collection of rows containing the data. |
PrimaryKey | DataColumn[] | Array of columns that act as the primary key. |
Constraints | ConstraintCollection | Constraints such as primary key and foreign key constraints. |
Common Methods
public void AcceptChanges();
public DataRow NewRow();
public void Load(IDataReader reader);
public DataRow Find(object[] keyValues);
public void Clear();
using System;
using System.Data;
class Example
{
static void Main()
{
// Create a DataTable with two columns.
DataTable table = new DataTable("Employees");
table.Columns.Add("Id", typeof(int));
table.Columns.Add("Name", typeof(string));
// Define primary key.
table.PrimaryKey = new[] { table.Columns["Id"] };
// Add rows.
table.Rows.Add(1, "Alice");
table.Rows.Add(2, "Bob");
// Find a row by primary key.
DataRow row = table.Rows.Find(1);
Console.WriteLine($\"Found: {row["Name"]}\");
}
}
Example: Loading Data from a Database
using System;
using System.Data;
using System.Data.SqlClient;
class LoadDemo
{
static void Main()
{
string connStr = "Data Source=.;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Customers", conn);
DataTable customers = new DataTable();
adapter.Fill(customers);
foreach (DataRow r in customers.Rows)
Console.WriteLine($"{r["CustomerID"]} - {r["CompanyName"]}");
}
}
}