Controlar eventos de DataTableHandling DataTable Events

El objeto DataTable proporciona una serie de eventos que una aplicación puede procesar.The DataTable object provides a series of events that can be processed by an application. En la siguiente tabla se describen los eventos de DataTable.The following table describes DataTable events.

eventoEvent DescripciónDescription
Initialized Se produce después de haber llamado al método EndInit de un objeto DataTable.Occurs after the EndInit method of a DataTable is called. Este evento está concebido principalmente para admitir escenarios en tiempo de diseño.This event is intended primarily to support design-time scenarios.
ColumnChanged Se produce después de cambiar correctamente un valor en un objeto DataColumn.Occurs after a value has been successfully changed in a DataColumn.
ColumnChanging Se produce cuando se ha enviado un valor para un objeto DataColumn.Occurs when a value has been submitted for a DataColumn.
RowChanged Se produce cuando se ha cambiado correctamente un valor de DataColumn o la propiedad RowState de un objeto DataRow en el objeto DataTable.Occurs after a DataColumn value or the RowState of a DataRow in the DataTable has been changed successfully.
RowChanging Se produce cuando se ha enviado un cambio para un valor DataColumn o la propiedad RowState de un objeto DataRow en el objeto DataTable.Occurs when a change has been submitted for a DataColumn value or the RowState of a DataRow in the DataTable.
RowDeleted Se produce después de marcar un objeto DataRow de un objeto DataTable como Deleted.Occurs after a DataRow in the DataTable has been marked as Deleted.
RowDeleting Se produce antes de marcar un objeto DataRow de un objeto DataTable como Deleted.Occurs before a DataRow in the DataTable is marked as Deleted.
TableCleared Se produce después de que una llamada al método Clear del objeto DataTable haya borrado correctamente todos los objetos DataRow.Occurs after a call to the Clear method of the DataTable has successfully cleared every DataRow.
TableClearing Se produce después de haber llamado al método Clear pero antes de que se inicie la operación Clear.Occurs after the Clear method is called but before the Clear operation begins.
TableNewRow Se produce después de crear un nuevo objeto DataRow mediante una llamada al método NewRow del objeto DataTable.Occurs after a new DataRow is created by a call to the NewRow method of the DataTable.
Disposed Se produce cuando el objeto DataTable se establece en Disposed.Occurs when the DataTable is Disposed. Se hereda de MarshalByValueComponent.Inherited from MarshalByValueComponent.

Nota

La mayoría de las operaciones que agregan o eliminan filas no generan eventos ColumnChanged ni ColumnChanging.Most operations that add or delete rows do not raise the ColumnChanged and ColumnChanging events. Sin embargo, el método ReadXml sí genera eventos ColumnChanged y ColumnChanging, a menos que XmlReadMode se establezca en DiffGram o se establezca en Auto cuando el documento XML que se lee es DiffGram.However, the ReadXml method does raise ColumnChanged and ColumnChanging events, unless the XmlReadMode is set to DiffGram or is set to Auto when the XML document being read is a DiffGram.

Advertencia

Es posible que los datos resulten dañados si se modifican en un DataSet desde el que se genera el evento RowChanged.Data corruption can occur if data is modified in a DataSet from which the RowChanged event is raised. No se producirá ninguna excepción si se produce este tipo de daño en los datos.No exception will be raised if such data corruption occurs.

La propiedad Constraints contiene una instancia de ConstraintCollection.The Constraints property holds a ConstraintCollection instance. La clase ConstraintCollection expone un evento CollectionChanged.The ConstraintCollection class exposes a CollectionChanged event. Este evento se activa cuando se agrega, modifica o quita una restricción de ConstraintCollection.This event fires when a constraint is added, modified, or removed from the ConstraintCollection.

La propiedad Columns contiene una instancia de DataColumnCollection.The Columns property holds a DataColumnCollection instance. La clase DataColumnCollection expone un evento CollectionChanged.The DataColumnCollection class exposes a CollectionChanged event. Este evento se activa cuando se agrega, modifica o quita un objeto DataColumn de DataColumnCollection.This event fires when a DataColumn is added, modified, or removed from the DataColumnCollection. Entre las modificaciones que generan el inicio del evento se encuentran los cambios en el nombre, el tipo, la expresión o la posición ordinal de una columna.Modifications that cause the event to fire include changes to the name, type, expression or ordinal position of a column.

La propiedad Tables de un objeto DataSet incluye una instancia de DataTableCollection.The Tables property of a DataSet holds a DataTableCollection instance. La clase DataTableCollection expone los eventos CollectionChanged y CollectionChanging.The DataTableCollection class exposes both a CollectionChanged and a CollectionChanging event. Estos eventos se activan cuando se agrega o se quita un objeto DataTable del DataSet.These events fire when a DataTable is added to or removed from the DataSet.

Los cambios en DataRows también pueden activar eventos de un objeto DataView asociado.Changes to DataRows can also trigger events for an associated DataView. La clase DataView expone un evento ListChanged que se activa cuando cambia un valor de DataColumn o cuando cambian la composición o el criterio de ordenación de la vista.The DataView class exposes a ListChanged event that fires when a DataColumn value changes or when the composition or sort order of the view changes. La clase DataRowView expone un evento PropertyChanged que se activa cuando cambia un valor de DataColumn asociado.The DataRowView class exposes a PropertyChanged event that fires when an associated DataColumn value changes.

Secuencia de operacionesSequence of Operations

A continuación se indica la secuencia de las operaciones que tienen lugar cuando se agrega, modifica o elimina un objeto DataRow.Here is the sequence of operations that occur when a DataRow is added, modified, or deleted:

  1. Se crea el registro propuesto y se aplican los cambios.Create the proposed record and apply any changes.

  2. Se comprueban las restricciones en columnas que no son de expresión.Check constraints for non-expression columns.

  3. Se generan los eventos RowChanging o RowDeleting, según corresponda.Raise the RowChanging or RowDeleting events as applicable.

  4. El registro propuesto se establece en el registro actual.Set the proposed record to be the current record.

  5. Se actualizan los índices asociados.Update any associated indexes.

  6. Se generan los eventos ListChanged de los objetos DataView asociados y los eventos PropertyChanged de los objetos DataRowView asociados.Raise ListChanged events for associated DataView objects and PropertyChanged events for associated DataRowView objects.

  7. Se evalúan todas las columnas de expresión, pero se retrasa la comprobación de las restricciones de estas columnas.Evaluate all expression columns, but delay checking any constraints on these columns.

  8. Se generan los eventos ListChanged de los objetos DataView asociados y los eventos PropertyChanged de los objetos DataRowView asociados a los que afecten las evaluaciones de la columna de expresión.Raise ListChanged events for associated DataView objects and PropertyChanged events for associated DataRowView objects affected by the expression column evaluations.

  9. Se generan los eventos RowChanged o RowDeleted, según corresponda.Raise RowChanged or RowDeleted events as applicable.

  10. Se comprueban las restricciones en las columnas de expresión.Check constraints on expression columns.

Nota

Los cambios en las columnas de expresión nunca generan eventos DataTable.Changes to expression columns never raise DataTable events. Los cambios en las columnas de expresión solo generan eventos DataView y DataRowView.Changes to expression columns only raise DataView and DataRowView events. Las columnas de expresión pueden tener dependencias en otras columnas y se pueden evaluar varias veces durante una única operación de DataRow.Expression columns can have dependencies on multiple other columns, and can be evaluated multiple times during a single DataRow operation. Cada evaluación de expresión genera eventos, y una sola operación de DataRow puede generar varios eventos ListChanged y PropertyChanged cuando se ven afectadas columnas de expresión, que posiblemente incluyen varios eventos para la misma columna de expresión.Each expression evaluation raises events, and a single DataRow operation can raise multiple ListChanged and PropertyChanged events when expression columns are affected, possibly including multiple events for the same expression column.

Advertencia

No inicie una excepción NullReferenceException dentro del controlador de eventos RowChanged.Do not throw a NullReferenceException within the RowChanged event handler. Si se inicia una excepción NullReferenceException dentro del evento RowChanged de un objeto DataTable, el objeto DataTable resultará dañado.If a NullReferenceException is thrown within the RowChanged event of a DataTable, then the DataTable will be corrupted.

EjemploExample

En el ejemplo siguiente se muestra cómo crear controladores de eventos para los eventos RowChanged, RowChanging, RowDeleted, RowDeleting, ColumnChanged, ColumnChanging, TableNewRow, TableCleared y TableClearing.The following example demonstrates how to create event handlers for the RowChanged, RowChanging, RowDeleted, RowDeleting, ColumnChanged, ColumnChanging, TableNewRow, TableCleared, and TableClearing events. Cada controlador de eventos muestra resultado en la ventana de la consola cuando se activa.Each event handler displays output in the console window when it is fired.

static void DataTableEvents()
{
    DataTable table = new DataTable("Customers");
    // Add two columns, id and name.
    table.Columns.Add("id", typeof(int));
    table.Columns.Add("name", typeof(string));

    // Set the primary key. 
    table.Columns["id"].Unique = true;
    table.PrimaryKey = new DataColumn[] { table.Columns["id"] };

    // Add a RowChanged event handler.
    table.RowChanged += new DataRowChangeEventHandler(Row_Changed);

    // Add a RowChanging event handler.
    table.RowChanging += new DataRowChangeEventHandler(Row_Changing);

    // Add a RowDeleted event handler.
    table.RowDeleted += new DataRowChangeEventHandler(Row_Deleted);

    // Add a RowDeleting event handler.
    table.RowDeleting += new DataRowChangeEventHandler(Row_Deleting);

    // Add a ColumnChanged event handler.
    table.ColumnChanged += new
        DataColumnChangeEventHandler(Column_Changed);

    // Add a ColumnChanging event handler.
    table.ColumnChanging += new
        DataColumnChangeEventHandler(Column_Changing);

    // Add a TableNewRow event handler.
    table.TableNewRow += new
        DataTableNewRowEventHandler(Table_NewRow);

    // Add a TableCleared event handler.
    table.TableCleared += new
        DataTableClearEventHandler(Table_Cleared);

    // Add a TableClearing event handler.
    table.TableClearing += new
        DataTableClearEventHandler(Table_Clearing);

    // Add a customer.
    DataRow row = table.NewRow();
    row["id"] = 1;
    row["name"] = "Customer1";
    table.Rows.Add(row);

    table.AcceptChanges();

    // Change the customer name.
    table.Rows[0]["name"] = "ChangedCustomer1";

    // Delete the row.
    table.Rows[0].Delete();

    // Clear the table.
    table.Clear();
}


private static void Row_Changed(object sender, DataRowChangeEventArgs e)
{
    Console.WriteLine("Row_Changed Event: name={0}; action={1}",
        e.Row["name"], e.Action);
}

private static void Row_Changing(object sender, DataRowChangeEventArgs e)
{
    Console.WriteLine("Row_Changing Event: name={0}; action={1}",
        e.Row["name"], e.Action);
}

private static void Row_Deleted(object sender, DataRowChangeEventArgs e)
{
    Console.WriteLine("Row_Deleted Event: name={0}; action={1}",
        e.Row["name", DataRowVersion.Original], e.Action);
}

private static void Row_Deleting(object sender,
DataRowChangeEventArgs e)
{
    Console.WriteLine("Row_Deleting Event: name={0}; action={1}",
        e.Row["name"], e.Action);
}

private static void Column_Changed(object sender, DataColumnChangeEventArgs e)
{
    Console.WriteLine("Column_Changed Event: ColumnName={0}; RowState={1}",
        e.Column.ColumnName, e.Row.RowState);
}

private static void Column_Changing(object sender, DataColumnChangeEventArgs e)
{
    Console.WriteLine("Column_Changing Event: ColumnName={0}; RowState={1}",
        e.Column.ColumnName, e.Row.RowState);
}

private static void Table_NewRow(object sender,
    DataTableNewRowEventArgs e)
{
    Console.WriteLine("Table_NewRow Event: RowState={0}",
        e.Row.RowState.ToString());
}

private static void Table_Cleared(object sender, DataTableClearEventArgs e)
{
    Console.WriteLine("Table_Cleared Event: TableName={0}; Rows={1}",
        e.TableName, e.Table.Rows.Count.ToString());
}

private static void Table_Clearing(object sender, DataTableClearEventArgs e)
{
    Console.WriteLine("Table_Clearing Event: TableName={0}; Rows={1}",
        e.TableName, e.Table.Rows.Count.ToString());
}
Private Sub DataTableEvents()

    Dim table As DataTable = New DataTable("Customers")
    ' Add two columns, id and name.
    table.Columns.Add("id", Type.GetType("System.Int32"))
    table.Columns.Add("name", Type.GetType("System.String"))

    ' Set the primary key.
    table.Columns("id").Unique = True
    table.PrimaryKey = New DataColumn() {table.Columns("id")}

    ' Add a RowChanged event handler.
    AddHandler table.RowChanged, _
           New DataRowChangeEventHandler(AddressOf Row_Changed)

    ' Add a RowChanging event handler.
    AddHandler table.RowChanging, _
           New DataRowChangeEventHandler(AddressOf Row_Changing)

    ' Add a RowDeleted event handler.
    AddHandler table.RowDeleted, New _
           DataRowChangeEventHandler(AddressOf Row_Deleted)

    ' Add a RowDeleting event handler.
    AddHandler table.RowDeleting, New _
           DataRowChangeEventHandler(AddressOf Row_Deleting)

    ' Add a ColumnChanged event handler.
    AddHandler table.ColumnChanged, _
           New DataColumnChangeEventHandler(AddressOf Column_Changed)

    ' Add a ColumnChanging event handler for the table.
    AddHandler table.ColumnChanging, New _
           DataColumnChangeEventHandler(AddressOf Column_Changing)

    ' Add a TableNewRow event handler.
    AddHandler table.TableNewRow, New _
           DataTableNewRowEventHandler(AddressOf Table_NewRow)

    ' Add a TableCleared event handler.
    AddHandler table.TableCleared, New _
           DataTableClearEventHandler(AddressOf Table_Cleared)

    ' Add a TableClearing event handler.
    AddHandler table.TableClearing, New _
           DataTableClearEventHandler(AddressOf Table_Clearing)

    ' Add a customer.
    Dim row As DataRow = table.NewRow()
    row("id") = 1
    row("name") = "Customer1"
    table.Rows.Add(row)

    table.AcceptChanges()

    ' Change the customer name.
    table.Rows(0).Item("name") = "ChangedCustomer1"

    ' Delete the row.
    table.Rows(0).Delete()

    ' Clear the table.
    table.Clear()
End Sub


Private Sub Row_Changed(ByVal sender As Object, _
    ByVal e As DataRowChangeEventArgs)
    Console.WriteLine("Row_Changed Event: name={0}; action={1}", _
     e.Row("name"), e.Action)
End Sub

Private Sub Row_Changing(ByVal sender As Object, _
    ByVal e As DataRowChangeEventArgs)
    Console.WriteLine("Row_Changing Event: name={0}; action={1}", _
     e.Row("name"), e.Action)
End Sub

Private Sub Row_Deleted(ByVal sender As Object, _
    ByVal e As DataRowChangeEventArgs)
    Console.WriteLine("Row_Deleted Event: name={0}; action={1}", _
     e.Row("name", DataRowVersion.Original), e.Action)
End Sub

Private Sub Row_Deleting(ByVal sender As Object, _
    ByVal e As DataRowChangeEventArgs)
    Console.WriteLine("Row_Deleting Event: name={0}; action={1}", _
       e.Row("name"), e.Action)
End Sub

Private Sub Column_Changed(ByVal sender As Object, _
    ByVal e As DataColumnChangeEventArgs)
    Console.WriteLine("Column_Changed Event: ColumnName={0}; RowState={1}", _
       e.Column.ColumnName, e.Row.RowState)
End Sub

Private Sub Column_Changing(ByVal sender As Object, _
    ByVal e As DataColumnChangeEventArgs)
    Console.WriteLine("Column_Changing Event: ColumnName={0}; RowState={1}", _
       e.Column.ColumnName, e.Row.RowState)
End Sub

Private Sub Table_NewRow(ByVal sender As Object, _
ByVal e As DataTableNewRowEventArgs)
    Console.WriteLine("Table_NewRow Event: RowState={0}", _
       e.Row.RowState.ToString())
End Sub

Private Sub Table_Cleared(ByVal sender As Object, _
    ByVal e As DataTableClearEventArgs)
    Console.WriteLine("Table_Cleared Event: TableName={0}; Rows={1}", _
       e.TableName, e.Table.Rows.Count.ToString())
End Sub

Private Sub Table_Clearing(ByVal sender As Object, _
    ByVal e As DataTableClearEventArgs)
    Console.WriteLine("Table_Clearing Event: TableName={0}; Rows={1}", _
       e.TableName, e.Table.Rows.Count.ToString())
End Sub

Vea tambiénSee also