DataRow Class

The DataRow class represents a single row of data within a DataTable. It is a fundamental building block for working with data in ADO.NET, allowing you to access, manipulate, and manage individual records.

Each DataRow object holds the values for a specific record, with each value corresponding to a DataColumn in the parent DataTable.

Key Features and Properties

Accessing Data

You can access the data within a DataRow using several methods:

Example: Accessing Row Data


DataTable customersTable = new DataTable("Customers");
customersTable.Columns.Add("CustomerID", typeof(int));
customersTable.Columns.Add("CompanyName", typeof(string));
customersTable.Columns.Add("ContactName", typeof(string));

// Add a new row
DataRow newRow = customersTable.NewRow();
newRow["CustomerID"] = 1;
newRow["CompanyName"] = "Exotic Liquids";
newRow["ContactName"] = "Charlotte Cooper";
customersTable.Rows.Add(newRow);

// Accessing data from an existing row
DataRow firstRow = customersTable.Rows[0];
int id = (int)firstRow["CustomerID"]; // Access by column name
string company = firstRow[1].ToString(); // Access by column index
string contact = firstRow.Field<string>("ContactName"); // Using Field extensions

Console.WriteLine($"ID: {id}, Company: {company}, Contact: {contact}");
            

Row State

A DataRow has a state that indicates its current status within the DataTable. This state is crucial when dealing with changes and updates:

You can check the row state using the RowState property.

Accessing Original and Current Values

When a row is modified, it retains both its original values and its current (modified) values. You can access these using the OriginalRow property or by specifying the DataRowVersion when accessing data:

Example: Accessing Original and Current Values


// Assume 'row' is a DataRow that has been modified
Console.WriteLine($"Current Company Name: {row["CompanyName"]}");
Console.WriteLine($"Original Company Name: {row["CompanyName", DataRowVersion.Original]}");

// To get the entire original row
DataRow originalRow = row.Table.Rows.Find(row["CustomerID"]); // Or other primary key lookup
if (originalRow != null) {
    Console.WriteLine($"Original Contact Name: {originalRow["ContactName"]}");
}
            

Row Error Information

DataRow provides properties for managing row-level errors:

Modifying Row Data

You can directly assign new values to the DataRow using its indexer:


// Assume 'row' is an existing DataRow
row["ContactName"] = "Janet Flowers";
row["Email"] = "janet.flowers@example.com"; // If 'Email' column exists
row.AcceptChanges(); // To mark the row as unchanged
            

Deleting Rows

To delete a row, call the Delete() method:


// Assuming 'rowToDelete' is the DataRow to be deleted
rowToDelete.Delete();
// Changes are staged. Call table.AcceptChanges() to finalize deletion.
            

Related Concepts