Manipulação de eventos de DataTableHandling DataTable Events

O DataTable objeto fornece uma série de eventos que podem ser processados por um aplicativo.The DataTable object provides a series of events that can be processed by an application. A tabela a seguir DataTable descreve os eventos.The following table describes DataTable events.

eventoEvent DescriçãoDescription
Initialized Ocorre depois que EndInit o método de DataTable um é chamado.Occurs after the EndInit method of a DataTable is called. Esse evento destina-se principalmente ao suporte a cenários de tempo de design.This event is intended primarily to support design-time scenarios.
ColumnChanged Ocorre depois que um valor é alterado com êxito em um DataColumn.Occurs after a value has been successfully changed in a DataColumn.
ColumnChanging Ocorre quando um valor é enviado para um DataColumn.Occurs when a value has been submitted for a DataColumn.
RowChanged Ocorre depois que DataColumn um valor ou RowState o de DataRow um no DataTable foi alterado com êxito.Occurs after a DataColumn value or the RowState of a DataRow in the DataTable has been changed successfully.
RowChanging Ocorre quando uma alteração DataColumn é enviada para um valor ou o RowState de um DataRow no DataTable.Occurs when a change has been submitted for a DataColumn value or the RowState of a DataRow in the DataTable.
RowDeleted Ocorre depois que DataRow um DataTable no é marcado como Deleted.Occurs after a DataRow in the DataTable has been marked as Deleted.
RowDeleting Ocorre antes que DataRow um DataTable no seja marcado como Deleted.Occurs before a DataRow in the DataTable is marked as Deleted.
TableCleared Ocorre depois que uma chamada para Clear o método DataTable de foi limpa com êxito a DataRowcada.Occurs after a call to the Clear method of the DataTable has successfully cleared every DataRow.
TableClearing Ocorre depois que Clear o método é chamado, mas Clear antes do início da operação.Occurs after the Clear method is called but before the Clear operation begins.
TableNewRow Ocorre depois que um DataRow novo é criado por uma chamada para NewRow o método do DataTable.Occurs after a new DataRow is created by a call to the NewRow method of the DataTable.
Disposed Ocorre quando o DataTable é Disposed.Occurs when the DataTable is Disposed. Herdada de MarshalByValueComponent.Inherited from MarshalByValueComponent.

Observação

A maioria das operações que adicionam ou excluem linhas ColumnChanged não ColumnChanging geram os eventos e.Most operations that add or delete rows do not raise the ColumnChanged and ColumnChanging events. No entanto ReadXml , o método ColumnChanged gera ColumnChanging XmlReadMode e eventos, a menos que seja DiffGram definido como ou seja Auto definido como quando o documento XML que está DiffGramsendo lido for um.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.

Aviso

Os dados corrompidos podem ocorrer se os dados são DataSet modificados em RowChanged um do qual o evento é gerado.Data corruption can occur if data is modified in a DataSet from which the RowChanged event is raised. Nenhuma exceção será gerada se ocorrer corrupção de dados.No exception will be raised if such data corruption occurs.

A Constraints propriedade contém uma ConstraintCollection instância.The Constraints property holds a ConstraintCollection instance. A ConstraintCollection classe expõe um CollectionChanged evento.The ConstraintCollection class exposes a CollectionChanged event. Esse evento é acionado quando uma restrição é adicionada, modificada ou removida do ConstraintCollection.This event fires when a constraint is added, modified, or removed from the ConstraintCollection.

A Columns propriedade contém uma DataColumnCollection instância.The Columns property holds a DataColumnCollection instance. A DataColumnCollection classe expõe um CollectionChanged evento.The DataColumnCollection class exposes a CollectionChanged event. Esse evento é acionado DataColumn quando um é adicionado, modificado ou removido DataColumnCollectiondo.This event fires when a DataColumn is added, modified, or removed from the DataColumnCollection. As modificações que fazem com que o evento seja acionado incluem alterações no nome, tipo, expressão ou posição ordinal de uma coluna.Modifications that cause the event to fire include changes to the name, type, expression or ordinal position of a column.

A Tables propriedade de um DataSet mantém uma DataTableCollection instância.The Tables property of a DataSet holds a DataTableCollection instance. A DataTableCollection classe expõe tanto um CollectionChanged quanto um CollectionChanging evento.The DataTableCollection class exposes both a CollectionChanged and a CollectionChanging event. Esses eventos são acionados DataTable quando um é adicionado ou removido DataSetdo.These events fire when a DataTable is added to or removed from the DataSet.

As alterações DataRows em também podem disparar eventos para um DataViewassociado.Changes to DataRows can also trigger events for an associated DataView. A DataView classe expõe um ListChanged evento que é acionado DataColumn quando um valor é alterado ou quando a ordem de composição ou de classificação da exibição é alterada.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. A DataRowView classe expõe um PropertyChanged evento que é acionado quando DataColumn um valor associado é alterado.The DataRowView class exposes a PropertyChanged event that fires when an associated DataColumn value changes.

Sequência de operaçõesSequence of Operations

Aqui está a sequência de operações que ocorrem quando uma DataRow é adicionada, modificada ou excluída:Here is the sequence of operations that occur when a DataRow is added, modified, or deleted:

  1. Crie o registro proposto e aplique as alterações.Create the proposed record and apply any changes.

  2. Verifique as restrições de colunas que não são de expressão.Check constraints for non-expression columns.

  3. Gere os RowChanging eventos RowDeleting ou conforme aplicável.Raise the RowChanging or RowDeleting events as applicable.

  4. Defina o registro proposto como o registro atual.Set the proposed record to be the current record.

  5. Atualize todos os índices associados.Update any associated indexes.

  6. Gerar ListChanged eventos para objetos DataView associados e PropertyChanged eventos para objetos DataRowView associados.Raise ListChanged events for associated DataView objects and PropertyChanged events for associated DataRowView objects.

  7. Avalie todas as colunas de expressão, mas adie a verificação de qualquer restrição nessas colunas.Evaluate all expression columns, but delay checking any constraints on these columns.

  8. Gerar ListChanged eventos para objetos DataView associados e PropertyChanged eventos para objetos DataRowView associados afetados pelas avaliações de coluna de expressão.Raise ListChanged events for associated DataView objects and PropertyChanged events for associated DataRowView objects affected by the expression column evaluations.

  9. Gerar RowChanged ouRowDeleted eventos conforme aplicável.Raise RowChanged or RowDeleted events as applicable.

  10. Verifique as restrições nas colunas de expressão.Check constraints on expression columns.

Observação

As alterações nas colunas de expressão DataTable nunca geram eventos.Changes to expression columns never raise DataTable events. As alterações nas colunas de expressão DataView geram e DataRowView apenas eventos.Changes to expression columns only raise DataView and DataRowView events. As colunas de expressão podem ter dependências em várias outras colunas e podem ser avaliadas várias vezes DataRow durante uma única operação.Expression columns can have dependencies on multiple other columns, and can be evaluated multiple times during a single DataRow operation. Cada avaliação de expressão gera eventos e uma única DataRow operação pode gerar vários ListChanged eventos PropertyChanged e quando as colunas de expressão são afetadas, possivelmente incluindo vários eventos para a mesma coluna de expressão.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.

Aviso

Não lance um NullReferenceException dentro do manipulador RowChanged de eventos.Do not throw a NullReferenceException within the RowChanged event handler. Se um NullReferenceException for lançado RowChanged no evento de a DataTable, o DataTable será corrompido.If a NullReferenceException is thrown within the RowChanged event of a DataTable, then the DataTable will be corrupted.

ExemploExample

O exemplo a seguir demonstra como criar manipuladores de eventos para RowChangedos RowChangingeventos RowDeleted, RowDeleting, ColumnChanged, ColumnChanging TableNewRow,, TableCleared,, TableClearing e.The following example demonstrates how to create event handlers for the RowChanged, RowChanging, RowDeleted, RowDeleting, ColumnChanged, ColumnChanging, TableNewRow, TableCleared, and TableClearing events. Cada manipulador de eventos exibe a saída na janela do console quando ela é acionada.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 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

Consulte tambémSee also