DataRowCollection Class (System.Data)

Toggle Dark Mode

Overview

The DataRowCollection class provides a collection of DataRow objects for a DataTable. It implements IList, ICollection, and IEnumerable interfaces, allowing indexed access, enumeration, and collection manipulation.

Syntax

public sealed class DataRowCollection : IList, ICollection, IEnumerable

Properties

NameTypeDescription
CountintGets the number of rows in the collection.
Item[int index]DataRowGets the DataRow at the specified index.
Item[string rowName]DataRowGets the DataRow with the specified primary key value.

Methods

Add

Adds a new DataRow to the collection.

public DataRow Add(params object[] values)

Clear

Removes all rows from the collection.

public void Clear()

Contains

Determines whether a DataRow with the specified primary key value exists.

public bool Contains(object key)

CopyTo

Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array.

public void CopyTo(Array array, int index)

Find

Finds a row based on its primary key value.

public DataRow Find(object key)

Remove

Removes the specified DataRow from the collection.

public void Remove(DataRow row)

Remarks

The DataRowCollection is typically accessed through the Rows property of a DataTable.

When a primary key is defined for the table, you can retrieve rows using Find or the string indexer. The collection is not thread‑safe for write operations.

Examples

The following example demonstrates how to create a DataTable, add rows to its DataRowCollection, and retrieve a row by primary key.

using System;
using System.Data;

class Program {
    static void Main() {
        // Create a DataTable with two columns.
        DataTable table = new DataTable("Employees");
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.PrimaryKey = new[] { table.Columns["ID"] };

        // Add rows using the DataRowCollection.
        DataRowCollection rows = table.Rows;
        rows.Add(1, "Alice");
        rows.Add(2, "Bob");
        rows.Add(3, "Charlie");

        // Find a row by primary key.
        DataRow found = rows.Find(2);
        Console.WriteLine($\"Found employee: {found["Name"]}\");
    }
}