DataTable Class
The DataTable
class represents an in-memory collection of data that is organized into tables. It is a core component of ADO.NET and is used to store and manipulate data from various sources, such as databases, XML files, or business objects.
Overview
A DataTable
is analogous to a single table in a relational database. It contains:
- A collection of
DataColumn
objects, which define the schema of the table (column names, data types, constraints). - A collection of
DataRow
objects, which represent the individual records within the table. - A collection of
Constraint
objects (like unique constraints and foreign key constraints) that enforce data integrity.
DataTable
is a versatile class that can be used independently or as part of a DataSet
, which is a collection of related DataTable
objects.
Key Properties and Methods
Properties
Property | Description |
---|---|
Columns |
Gets a collection of DataColumn objects that define the schema of the table. |
Rows |
Gets a collection of DataRow objects that represent the data in the table. |
TableName |
Gets or sets the name of the table. |
DataSet |
Gets the DataSet that contains this table. |
HasErrors |
Gets a value indicating whether any row in the table has an error. |
Methods
Method | Description |
---|---|
NewRow() |
Creates a new DataRow with the same schema as the table. |
Rows.Add(DataRow row) |
Adds a specified DataRow to the table. |
AcceptChanges() |
Accepts all changes made to the table since the last time AcceptChanges was called. |
RejectChanges() |
Reverts all changes made to the table since the last time AcceptChanges was called. |
Select(string filterExpression) |
Returns an array of DataRow objects that match the specified filter expression. |
Creating and Populating a DataTable
You can create a DataTable
programmatically and populate it with data.
using System.Data;
// Create a new DataTable
DataTable productsTable = new DataTable("Products");
// Define the columns
productsTable.Columns.Add("ProductID", typeof(int));
productsTable.Columns.Add("ProductName", typeof(string));
productsTable.Columns.Add("Price", typeof(decimal));
// Set primary key
productsTable.PrimaryKey = new DataColumn[] { productsTable.Columns["ProductID"] };
// Create a new DataRow
DataRow newRow = productsTable.NewRow();
newRow["ProductID"] = 1;
newRow["ProductName"] = "Laptop";
newRow["Price"] = 1200.50m;
// Add the row to the table
productsTable.Rows.Add(newRow);
// Add another row
productsTable.Rows.Add(2, "Keyboard", 75.00m);
// Add a third row using a more explicit method
DataRow row3 = productsTable.NewRow();
row3[0] = 3; // Access by column index
row3[1] = "Mouse";
row3["Price"] = 25.99m;
productsTable.Rows.Add(row3);
// Iterate through rows
Console.WriteLine("Products:");
foreach (DataRow row in productsTable.Rows)
{
Console.WriteLine($"ID: {row["ProductID"]}, Name: {row["ProductName"]}, Price: {row["Price"]}");
}
Filtering and Sorting
The Select
method allows you to filter rows based on an expression. You can also use DataView
for more advanced sorting and filtering.
// Assuming productsTable is already populated as above
// Filter for products with price greater than 100
DataRow[] expensiveProducts = productsTable.Select("Price > 100");
Console.WriteLine("\nExpensive Products:");
foreach (DataRow row in expensiveProducts)
{
Console.WriteLine($"ID: {row["ProductID"]}, Name: {row["ProductName"]}, Price: {row["Price"]}");
}
// Sort the table by ProductName
DataRow[] sortedProducts = productsTable.Select("", "ProductName ASC");
Console.WriteLine("\nProducts Sorted by Name:");
foreach (DataRow row in sortedProducts)
{
Console.WriteLine($"ID: {row["ProductID"]}, Name: {row["ProductName"]}, Price: {row["Price"]}");
}
DataTable
.
DataRow States
Each DataRow
has a state that indicates its current status:
Added
: The row is new and has not been sent to the data source.Modified
: The row's data has been changed since it was loaded or last accepted.Deleted
: The row has been deleted.Unchanged
: The row has not been changed since it was loaded or last accepted.
You can access the original version of a row using the `Original` version property when checking for changes.
Conclusion
The DataTable
class is a fundamental building block for data manipulation in ADO.NET. Its ability to store, filter, and sort data in memory makes it highly efficient for working with data disconnected from its source.