DataTable Class
The DataTable class in ADO.NET represents an in-memory collection of data. It is a core component for working with disconnected data, allowing you to store, retrieve, and manipulate tabular data independently of a data source. A DataTable is part of a DataSet, which can contain multiple DataTable objects.
Key Features and Functionality
- Schema Definition: A
DataTablehas a defined schema consisting ofDataColumnobjects, which specify the structure of the data, including column names, data types, and constraints. - Data Storage: It stores data in
DataRowobjects, each representing a single record within the table. - Data Manipulation: You can perform CRUD (Create, Read, Update, Delete) operations on
DataRowobjects. - Filtering and Sorting: The
DataViewclass provides powerful capabilities for filtering, sorting, and searching data within aDataTablewithout modifying the original data. - Relationships:
DataTableobjects can participate in relations defined within aDataSet, enabling navigation between related tables. - Constraints: You can enforce data integrity by defining constraints such as unique constraints and foreign key constraints.
Creating and Populating a DataTable
You can create a DataTable programmatically or load data from a data source. Here's an example of creating a simple DataTable:
C# Example
using System;
using System.Data;
// Create a new DataTable
DataTable productsTable = new DataTable("Products");
// Define columns
DataColumn idColumn = new DataColumn("ProductID", typeof(int));
idColumn.AutoIncrement = true; // Auto-incrementing ID
idColumn.AutoIncrementSeed = 1;
idColumn.AutoIncrementStep = 1;
idColumn.AllowDBNull = false; // Cannot be null
DataColumn nameColumn = new DataColumn("ProductName", typeof(string));
nameColumn.AllowDBNull = false; // Cannot be null
nameColumn.MaxLength = 100;
DataColumn priceColumn = new DataColumn("Price", typeof(decimal));
priceColumn.AllowDBNull = true; // Can be null
// Add columns to the DataTable
productsTable.Columns.Add(idColumn);
productsTable.Columns.Add(nameColumn);
productsTable.Columns.Add(priceColumn);
// Add a primary key constraint
DataKey primaryKey = new DataKey(idColumn);
productsTable.PrimaryKey = new DataColumn[] { idColumn };
// Add some rows
DataRow row1 = productsTable.NewRow();
row1["ProductName"] = "Laptop";
row1["Price"] = 1200.50m;
productsTable.Rows.Add(row1);
DataRow row2 = productsTable.NewRow();
row2["ProductName"] = "Keyboard";
row2["Price"] = 75.00m;
productsTable.Rows.Add(row2);
DataRow row3 = productsTable.NewRow();
row3["ProductName"] = "Mouse";
// Price is intentionally left null for demonstration
productsTable.Rows.Add(row3);
// Accessing data
Console.WriteLine($"Total rows: {productsTable.Rows.Count}");
foreach (DataRow row in productsTable.Rows)
{
Console.WriteLine($"ID: {row["ProductID"]}, Name: {row["ProductName"]}, Price: {(row["Price"] == DBNull.Value ? "N/A" : row["Price"].ToString())}");
}
DataTable Operations
Adding and Deleting Rows
Use NewRow() to create a new row and Rows.Add() to add it. Rows can be deleted using Rows.Remove() or Rows.RemoveAt().
Finding Rows
You can find rows using the Select() method, which returns an array of DataRow objects that match a filter expression.
Finding rows with price > 100
DataRow[] expensiveProducts = productsTable.Select("Price > 100");
foreach (DataRow row in expensiveProducts)
{
Console.WriteLine($"Expensive Product: {row["ProductName"]}");
}
Updating Rows
To update a row, first find it using its primary key or by selecting it, then modify the values of its columns.
Accepting Changes
The AcceptChanges() method marks all changes made since the last AcceptChanges() call as accepted. This is useful for managing changes before committing them to a data source.
DataTable vs. DataSet
While a DataTable represents a single table of data, a DataSet is a collection of one or more DataTable objects, along with relationships and constraints between them. A DataSet is often used to represent an entire database or a significant portion of it.
| Feature | DataTable | DataSet |
|---|---|---|
| Data Representation | A single table of data. | A collection of related tables, resembling a database. |
| Structure | Contains DataColumns and DataRows. |
Contains multiple DataTable objects. |
| Relationships | Can participate in relationships defined in a DataSet. |
Defines and manages relationships between its contained DataTables. |
Conclusion
The DataTable is a fundamental building block in ADO.NET for managing in-memory data. Its flexibility and rich feature set make it an indispensable tool for data-centric applications.