DataRow Objects

Understanding DataRow Objects in ADO.NET

The DataRow object represents a single row of data within a DataTable. It is a fundamental building block for managing data in ADO.NET, allowing you to access, modify, and interact with individual records.

Key Properties and Methods

DataRow objects provide several properties and methods to work with the data they contain:

Properties

Methods

Working with DataRow Values

You can access and modify column values in a DataRow using its index, column name, or the DataColumn object itself. It's important to handle potential DBNull.Value when retrieving data.

Example: Accessing and Modifying Data


using System;
using System.Data;

// Assume 'dt' is a DataTable with a 'ProductName' column (string) and 'Price' column (decimal)

// Example of creating a DataTable and adding a row (for context)
DataTable dt = new DataTable();
dt.Columns.Add("ProductID", typeof(int));
dt.Columns.Add("ProductName", typeof(string));
dt.Columns.Add("Price", typeof(decimal));

DataRow newRow = dt.NewRow();
newRow["ProductID"] = 1;
newRow["ProductName"] = "Chai";
newRow["Price"] = 18.00m;
dt.Rows.Add(newRow);

// --- Accessing Data ---
DataRow firstRow = dt.Rows[0]; // Get the first row

// Access by column name
string productName = firstRow["ProductName"].ToString();
Console.WriteLine($"Product Name: {productName}");

// Access by ordinal position (ProductID is at index 0)
int productId = (int)firstRow[0];
Console.WriteLine($"Product ID: {productId}");

// Accessing a potentially null value
object priceObject = firstRow["Price"];
decimal price = (priceObject == DBNull.Value) ? 0.0m : (decimal)priceObject;
Console.WriteLine($"Price: {price}");

// --- Modifying Data ---
firstRow["Price"] = 19.50m; // Update the price
firstRow.AcceptChanges(); // Commit the change

// --- Adding a New Row ---
DataRow anotherRow = dt.NewRow();
anotherRow["ProductID"] = 2;
anotherRow["ProductName"] = "Chang";
anotherRow["Price"] = 19.00m;
dt.Rows.Add(anotherRow);

// --- Deleting a Row ---
// Assume 'rowToDelete' is a DataRow object you want to delete
// rowToDelete.Delete();
// dt.AcceptChanges(); // This will remove the deleted row
            

Row States

The RowState property is crucial for understanding the status of a row within the data lifecycle:

By tracking row states, you can efficiently determine which rows need to be inserted, updated, or deleted when synchronizing your DataSet with a data source.

Relations and DataRow

DataRow objects play a key role in navigating relationships defined between DataTables within a DataSet. The GetChildRows() and GetParentRow() methods allow you to traverse these relationships, enabling complex data queries and manipulations.

Understanding and effectively utilizing DataRow objects is essential for building robust and efficient data-driven applications with ADO.NET.