DataTableCollection.CollectionChanged Event

Definition

Occurs after the DataTableCollection is changed because of DataTable objects being added or removed.

C#
public event System.ComponentModel.CollectionChangeEventHandler? CollectionChanged;
C#
public event System.ComponentModel.CollectionChangeEventHandler CollectionChanged;

Event Type

Examples

The following example demonstrates how to use the CollectionChanged event.

C#
public static void TableCollectionCollectionChanged()
{
    // create a DataSet with two tables
    DataSet dataSet = new DataSet();

    dataSet.Tables.CollectionChanged +=
        new System.ComponentModel.CollectionChangeEventHandler(
        Collection_Changed);

    // create Customer table
    DataTable custTable = new DataTable("Customers");
    custTable.Columns.Add("customerId",
        typeof(int)).AutoIncrement = true;
    custTable.Columns.Add("name",
        typeof(string));
    custTable.PrimaryKey = new DataColumn[] { custTable.Columns["customerId"] };

    // create Orders table
    DataTable orderTable = new DataTable("Orders");
    orderTable.Columns.Add("orderId",
        typeof(int)).AutoIncrement = true;
    orderTable.Columns.Add("customerId", typeof(int));
    orderTable.Columns.Add("amount", typeof(double));
    orderTable.PrimaryKey = new DataColumn[] { orderTable.Columns["orderId"] };

    dataSet.Tables.AddRange(new DataTable[] { custTable, orderTable });

    // remove all tables
    // check if table can be removed and then
    // remove it, cannot use a foreach when
    // removing items from a collection
    // equivalent to dataSet.Tables.Clear()
    while (dataSet.Tables.Count > 0)
    {
        DataTable table = dataSet.Tables[0];
        if (dataSet.Tables.CanRemove(table))
        {
            dataSet.Tables.RemoveAt(0);
        }
    }

    Console.WriteLine("dataSet has {0} tables",
        dataSet.Tables.Count);
}

private static void Collection_Changed(object sender,
    System.ComponentModel.CollectionChangeEventArgs e)
{
    Console.WriteLine("Collection_Changed Event: '{0}'\table element={1}",
        e.Action.ToString(), e.Element.ToString());
}

Remarks

For more information about how to handle events, see Handling and Raising Events.

Applies to

Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1