DataRow Class
Namespace: System.Data
Represents a row of data in a DataTable.
public sealed class DataRow : MarshalByRefObject, ICloneable
Remarks
The DataRow
class represents a single row of data within a DataTable. It provides access to the data within the row, as well as methods for manipulating the row's state and managing changes.
Constructors
-
DataRow(DataRowBuilder builder)
Initializes a new instance of the DataRow class.
Properties
-
object Item[int columnIndex]
Gets or sets the value of the column at the specified index.Returns: The value of the specified column.
-
object Item[string columnName]
Gets or sets the value of the column with the specified name.Returns: The value of the specified column.
-
DataRowState RowState
Gets the current state of the row.Returns: A DataRowState value indicating the state of the row.
-
DataTable Table
Gets the DataTable that contains this row.Returns: The DataTable that owns this row.
Methods
-
void AcceptChanges()
Accepts any changes made to this row since the last time AcceptChanges or RejectChanges was called.
-
object GetColumnError(int columnIndex)
Gets the error message for the specified column.Returns: The error message for the specified column, or an empty string if there is no error.
-
object GetColumnError(string columnName)
Gets the error message for the specified column.Returns: The error message for the specified column, or an empty string if there is no error.
-
void RejectChanges()
Rejects all changes made to this row since the last time AcceptChanges or RejectChanges was called.
-
void SetColumnError(int columnIndex, string error)
Sets the error message for the specified column.Parameters:
columnIndex
: The zero-based index of the column for which to set the error.error
: The error message to set for the column.
-
void SetColumnError(string columnName, string error)
Sets the error message for the specified column.Parameters:
columnName
: The name of the column for which to set the error.error
: The error message to set for the column.
Example
using System;
using System.Data;
public class Example
{
public static void Main()
{
// Create a DataTable.
DataTable dataTable = new DataTable("SampleTable");
// Add columns.
dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
// Add rows.
DataRow dataRow = dataTable.NewRow();
dataRow["ID"] = 1;
dataRow["Name"] = "Alice";
dataTable.Rows.Add(dataRow);
// Access data.
Console.WriteLine($"Row ID: {dataRow["ID"]}, Name: {dataRow["Name"]}");
// Modify data.
dataRow["Name"] = "Alicia";
Console.WriteLine($"Modified Name: {dataRow["Name"]}");
// Accept changes.
dataRow.AcceptChanges();
}
}