DataTable Overview

Last modified: September 15, 2023

The DataTable object is a core component of ADO.NET. It represents an in-memory cache of data that can be populated from a data source, manipulated by the user, and then persisted back to the source. A DataTable is similar to a relational database table, containing rows and columns.

Key Concepts

Structure

A DataTable is composed of:

Usage Scenarios

DataTable is useful in various scenarios:

Creating and Populating a DataTable

You can create a DataTable programmatically or have it generated by a DataAdapter when used with a DataSet.

Programmatic Creation


using System.Data;

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

// Define columns
DataColumn idColumn = new DataColumn("CustomerID", typeof(int));
idColumn.AutoIncrement = true; // Auto-incrementing ID
idColumn.AutoIncrementSeed = 1;
idColumn.AutoIncrementStep = 1;
idColumn.AllowDBNull = false; // Cannot be null
idColumn.Unique = true;      // Must be unique

DataColumn nameColumn = new DataColumn("Name", typeof(string));
nameColumn.AllowDBNull = false; // Cannot be null

DataColumn emailColumn = new DataColumn("Email", typeof(string));

// Add columns to the DataTable
customerTable.Columns.Add(idColumn);
customerTable.Columns.Add(nameColumn);
customerTable.Columns.Add(emailColumn);

// Set primary key
customerTable.PrimaryKey = new DataColumn[] { idColumn };

// Add rows
DataRow row1 = customerTable.NewRow();
row1["Name"] = "Alice Smith";
row1["Email"] = "alice.smith@example.com";
customerTable.Rows.Add(row1);

DataRow row2 = customerTable.NewRow();
row2["Name"] = "Bob Johnson";
row2["Email"] = "bob.johnson@example.com";
customerTable.Rows.Add(row2);

// You can also add rows directly without NewRow() if not specifying all columns or letting auto-increment handle it
// customerTable.Rows.Add(3, "Charlie Brown", "charlie.b@example.com");

Console.WriteLine("DataTable created and populated successfully.");
            

Using DataAdapter

When using a DataAdapter (like SqlDataAdapter) with a DataSet, the Fill() method automatically creates and populates the DataTable based on the query.

Note: The DataTable automatically infers schema from the data source when filled by a DataAdapter. You can also explicitly define the schema beforehand.

Working with DataRows and Columns

Accessing Data

You can access data within a DataTable using various methods:


// Accessing the first row's data
if (customerTable.Rows.Count > 0)
{
    DataRow firstRow = customerTable.Rows[0];
    Console.WriteLine($"First Customer ID: {firstRow["CustomerID"]}, Name: {firstRow["Name"]}");
}

// Filtering rows using Select()
DataRow[] filteredRows = customerTable.Select("Name LIKE 'A%'");
Console.WriteLine($"Customers starting with 'A': {filteredRows.Length}");
foreach (DataRow row in filteredRows)
{
    Console.WriteLine($"  - {row["Name"]}");
}
            

Modifying Data

Modifying data involves accessing a DataRow and changing its values. Changes are tracked by the row's RowState.


// Modifying a row
if (customerTable.Rows.Count > 0)
{
    DataRow rowToUpdate = customerTable.Rows[0];
    rowToUpdate["Email"] = "alice.updated@example.com";
    rowToUpdate.AcceptChanges(); // Mark changes as accepted
}

// Deleting a row
if (customerTable.Rows.Count > 1)
{
    DataRow rowToDelete = customerTable.Rows[1];
    rowToDelete.Delete(); // Mark row for deletion
    customerTable.AcceptChanges(); // Actually remove deleted rows
}
            

Key Properties and Methods

Property/Method Description
Columns Collection of DataColumn objects defining the table schema.
Rows Collection of DataRow objects containing the data.
PrimaryKey Array of DataColumn objects that define the primary key for the table.
TableName The name of the table.
NewRow() Creates a new DataRow object with the same schema as the table.
Select(filterExpression) Returns an array of DataRow objects that match the specified filter.
AcceptChanges() Accepts all changes made to the rows in the table.
HasErrors Returns true if any row in the table has errors.

Tip: Use the DataView object to create filtered, sorted, and grouped views of a DataTable without modifying the original table.

Conclusion

The DataTable is a versatile and powerful object in ADO.NET for managing in-memory data. Understanding its structure, creation, and manipulation is fundamental for building data-driven .NET applications.