ADO.NET DataRows

The DataRow object represents a single row of data within a DataTable. It provides access to the values in each column for that specific row.

Key Concepts

Accessing Column Values

You can access the value of a specific column in a DataRow by using the column's name or its ordinal position (index). It's recommended to use the column name for better readability and maintainability.


// Assuming 'row' is a DataRow and 'dt' is its DataTable
string customerName = row["CustomerName"].ToString();
int customerId = (int)row[0]; // Accessing by ordinal position
        

Modifying DataRow Values

You can modify the values in a DataRow before adding it to a DataTable or updating an existing row.


row["CustomerName"] = "New Customer Name";
row[1] = 12345; // Modifying by ordinal position
        

Row States

Each DataRow has a RowState property that indicates its current status. This is crucial when working with changes and submitting them to a data source.

Row Versioning

DataRow supports row versioning, allowing you to access the original and current versions of a row's data. This is useful for implementing optimistic concurrency.


// Accessing original value
string originalName = row["CustomerName", DataRowVersion.Original].ToString();
        

Handling Null Values

When a database column can contain null values, ADO.NET represents them using DBNull.Value. You should check for this value before attempting to use a column's value.


if (row["Email"] != DBNull.Value)
{
    string email = row["Email"].ToString();
    // Process email
}
else
{
    // Email is null
}
        

Common Operations

Iterating Through Rows

You can iterate through the rows of a DataTable using a foreach loop.


DataTable customersTable = dataSet.Tables["Customers"];
foreach (DataRow row in customersTable.Rows)
{
    Console.WriteLine($"Customer ID: {row["CustomerID"]}, Name: {row["Name"]}");
}
        

Finding Rows

The Select() method on a DataTable can be used to filter rows based on a filter expression.


DataRow[] foundRows = customersTable.Select("City = 'London'");
foreach (DataRow row in foundRows)
{
    Console.WriteLine($"Found: {row["Name"]}");
}
        
Tip: Use the Find() method for efficient row lookup when you have a primary key defined on the DataTable.

API Reference Highlights

DataRow Members

Member Description
this[int columnIndex] Gets or sets the value of the column at the specified ordinal position.
this[string columnName] Gets or sets the value of the column with the specified name.
this[string columnName, DataRowVersion version] Gets the value of the column with the specified name and row version.
RowError Gets or sets an error description for the row.
RowState Gets the current state of the row.
Table Gets the DataTable to which this row belongs.

Related Topics