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 aDataSet
.
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 newDataRow
object and then populate its values before adding it to theRows
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 callAcceptChanges()
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 withDataTable.Rows.Find()
.
DataTable Events
DataTable
exposes several events that allow you to hook into data manipulation actions:
RowChanging
andRowChanged
: Fired when a row is about to be changed or has just been changed.ColumnChanging
andColumnChanged
: Fired when a column's value is about to be changed or has just been changed.RowDeleting
andRowDeleted
: 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 ofDataColumn
objects that define the table's schema.Rows
: Gets a collection ofDataRow
objects that contain the table's data.PrimaryKey
: Gets or sets an array ofDataColumn
objects that represent the primary key of the table.DataSet
: Gets theDataSet
that contains this table.CaseSensitive
: Indicates whether string comparisons are case-sensitive.RemotingFormat
: Specifies how theDataTable
is serialized for remoting.