MSDN Documentation

DataTable Object

The DataTable object is a fundamental part of ADO.NET, representing an in-memory table of data. It provides a structured way to store and manipulate data, making it ideal for working with data retrieved from a data source or for creating custom data structures.

Core Components

A DataTable consists of the following key components:

  • Columns: Define the schema of the table. Each column has a name, data type, and can have constraints.
  • Rows: Contain the actual data for the table. Each row is an instance of a DataRow object.
  • Constraints: Enforce data integrity rules, such as unique values or foreign key relationships.
  • Relations: Define relationships between different DataTable objects within a DataSet.

Creating and Populating a DataTable

You can create a DataTable programmatically or by using a DataAdapter to fill it from a data source.

Programmatic Creation

Here's a C# example of creating a DataTable from scratch:


using System.Data;

// Create a new DataTable
DataTable customersTable = new DataTable("Customers");

// Add columns
customersTable.Columns.Add("CustomerID", typeof(int));
customersTable.Columns.Add("CompanyName", typeof(string));
customersTable.Columns.Add("ContactName", typeof(string));

// Set primary key
customersTable.PrimaryKey = new DataColumn[] { customersTable.Columns["CustomerID"] };

// Add rows
customersTable.Rows.Add(1, "Acme Corp", "John Doe");
customersTable.Rows.Add(2, "Beta Inc", "Jane Smith");
customersTable.Rows.Add(3, "Gamma Ltd", "Peter Jones");

// You can now access the data:
Console.WriteLine($"Number of customers: {customersTable.Rows.Count}");
Console.WriteLine($"Company name of first customer: {customersTable.Rows[0]["CompanyName"]}");
                

Using a DataAdapter

When working with databases, a DataAdapter (like SqlDataAdapter or OleDbDataAdapter) is typically used to fill a DataTable with data:


using System.Data;
using System.Data.SqlClient; // Or OleDb, etc.

// Assuming 'connectionString' is defined elsewhere
string connectionString = "Your_Connection_String_Here";
DataTable productsTable = new DataTable("Products");

using (SqlConnection connection = new SqlConnection(connectionString))
{
    string query = "SELECT ProductID, ProductName, UnitPrice FROM Products";
    SqlDataAdapter adapter = new SqlDataAdapter(query, connection);

    // The Fill method automatically creates columns and populates rows
    adapter.Fill(productsTable);
}

Console.WriteLine($"Number of products loaded: {productsTable.Rows.Count}");
                

Manipulating Data

DataTable provides methods for common data manipulation tasks:

  • Adding Rows: Use DataTable.NewRow() to create a new DataRow object and then populate its values before adding it to the Rows collection.
  • Updating Rows: Access a specific row by its index or by using a unique identifier and modify its values.
  • Deleting Rows: Use the RowState property to mark rows for deletion (Deleted) and then call AcceptChanges() to permanently remove them.
  • Finding Rows: Use the Select() method to filter rows based on specific criteria, or use the primary key to find a specific row with DataTable.Rows.Find().

DataTable Events

DataTable exposes several events that allow you to hook into data manipulation actions:

  • RowChanging and RowChanged: Fired when a row is about to be changed or has just been changed.
  • ColumnChanging and ColumnChanged: Fired when a column's value is about to be changed or has just been changed.
  • RowDeleting and RowDeleted: Fired when a row is about to be deleted or has just been deleted.
  • RowDeleted: Fired after a row has been deleted.

Key Properties

  • TableName: Gets or sets the name of the table.
  • Columns: Gets a collection of DataColumn objects that define the table's schema.
  • Rows: Gets a collection of DataRow objects that contain the table's data.
  • PrimaryKey: Gets or sets an array of DataColumn objects that represent the primary key of the table.
  • DataSet: Gets the DataSet that contains this table.
  • CaseSensitive: Indicates whether string comparisons are case-sensitive.
  • RemotingFormat: Specifies how the DataTable is serialized for remoting.