Gestione di eventi DataTableHandling DataTable Events

Nell'oggetto DataTable sono disponibili diversi eventi che possono essere elaborati da un'applicazione.The DataTable object provides a series of events that can be processed by an application. Nella tabella seguente vengono descritti gli eventi di DataTable.The following table describes DataTable events.

eventEvent DescrizioneDescription
Initialized Viene generato dopo la chiamata al metodo EndInit di DataTable.Occurs after the EndInit method of a DataTable is called. Questo evento è progettato principalmente per supportare gli scenari in fase di progettazione.This event is intended primarily to support design-time scenarios.
ColumnChanged Viene generato dopo la modifica di un valore in DataColumn.Occurs after a value has been successfully changed in a DataColumn.
ColumnChanging Viene generato quando un valore è stato inviato per una DataColumn.Occurs when a value has been submitted for a DataColumn.
RowChanged Viene generato dopo la modifica di un valore DataColumn o di RowState di DataRow nella DataTable.Occurs after a DataColumn value or the RowState of a DataRow in the DataTable has been changed successfully.
RowChanging Viene generato quando è stata inviata una modifica per un valore DataColumn o per RowState di DataRow nella DataTable.Occurs when a change has been submitted for a DataColumn value or the RowState of a DataRow in the DataTable.
RowDeleted Viene generato dopo che una DataRow nella DataTable è stata contrassegnata come Deleted.Occurs after a DataRow in the DataTable has been marked as Deleted.
RowDeleting Viene generato prima che una DataRow nella DataTable venga contrassegnata come Deleted.Occurs before a DataRow in the DataTable is marked as Deleted.
TableCleared Viene generato dopo che una chiamata al metodo Clear di DataTable ha cancellato correttamente ogni DataRow.Occurs after a call to the Clear method of the DataTable has successfully cleared every DataRow.
TableClearing Viene generato dopo una chiamata al metodo Clear ma prima dell'inizio dell'operazione Clear.Occurs after the Clear method is called but before the Clear operation begins.
TableNewRow Viene generato dopo la creazione di una nuova DataRow tramite una chiamata al metodo NewRow della DataTable.Occurs after a new DataRow is created by a call to the NewRow method of the DataTable.
Disposed Viene generato quando DataTable è Disposed.Occurs when the DataTable is Disposed. La proprietà viene ereditata da MarshalByValueComponent.Inherited from MarshalByValueComponent.

Nota

La maggior parte delle operazioni che aggiungono o eliminano righe non generano gli eventi ColumnChanged e ColumnChanging.Most operations that add or delete rows do not raise the ColumnChanged and ColumnChanging events. Tuttavia, il metodo ReadXml genera gli eventi ColumnChanged e ColumnChanging, a meno che XmlReadMode non sia impostato su DiffGram o su Auto quando il documento XML da leggere è un 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.

Avviso

I dati possono venire danneggiati se vengono modificati in un oggetto DataSet da cui viene generato l'evento RowChanged.Data corruption can occur if data is modified in a DataSet from which the RowChanged event is raised. In caso di danneggiamento dei dati, non viene generata alcuna eccezione.No exception will be raised if such data corruption occurs.

La proprietà Constraints contiene un'istanza di ConstraintCollection.The Constraints property holds a ConstraintCollection instance. La classe ConstraintCollection espone un evento CollectionChanged.The ConstraintCollection class exposes a CollectionChanged event. Questo evento viene attivato quando un vincolo viene aggiunto, modificato o rimosso da ConstraintCollection.This event fires when a constraint is added, modified, or removed from the ConstraintCollection.

La proprietà Columns contiene un'istanza di DataColumnCollection.The Columns property holds a DataColumnCollection instance. La classe DataColumnCollection espone un evento CollectionChanged.The DataColumnCollection class exposes a CollectionChanged event. Questo evento viene attivato quando una DataColumn viene aggiunta, modificata o rimossa da DataColumnCollection.This event fires when a DataColumn is added, modified, or removed from the DataColumnCollection. Le modifiche che causano l'attivazione dell'evento includono le modifiche al nome, tipo, espressione o posizione ordinale di una colonna.Modifications that cause the event to fire include changes to the name, type, expression or ordinal position of a column.

La proprietà Tables di DataSet contiene un'istanza di DataTableCollection.The Tables property of a DataSet holds a DataTableCollection instance. La classe DataTableCollection espone sia un evento CollectionChanged sia un evento CollectionChanging.The DataTableCollection class exposes both a CollectionChanged and a CollectionChanging event. Questi eventi vengono attivati quando una DataTable viene aggiunta, modificata o rimossa dal DataSet.These events fire when a DataTable is added to or removed from the DataSet.

Le modifiche a DataRows possono attivare anche eventi per un oggetto DataView associato.Changes to DataRows can also trigger events for an associated DataView. La classe DataView espone un evento ListChanged che viene attivato quando viene modificato un valore DataColumn oppure la composizione o l'ordine della visualizzazione.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 classe DataRowView espone un evento PropertyChanged che viene attivato quando viene modificato valore DataColumn associato.The DataRowView class exposes a PropertyChanged event that fires when an associated DataColumn value changes.

Sequenza delle operazioniSequence of Operations

Di seguito è riportata la sequenza delle operazioni che si verificano quando una DataRow viene aggiunta, modificata o eliminata:Here is the sequence of operations that occur when a DataRow is added, modified, or deleted:

  1. Creare il record proposto e applicare eventuali modifiche.Create the proposed record and apply any changes.

  2. Verificare i vincoli per le colonne non espressioni.Check constraints for non-expression columns.

  3. Generare gli eventi RowChanging o RowDeleting come applicabile.Raise the RowChanging or RowDeleting events as applicable.

  4. Impostare il record proposto come record corrente.Set the proposed record to be the current record.

  5. Aggiornare gli eventuali indici associati.Update any associated indexes.

  6. Generare gli eventi ListChanged per gli oggetti DataView associati e gli eventi PropertyChanged per gli oggetti DataRowView associati.Raise ListChanged events for associated DataView objects and PropertyChanged events for associated DataRowView objects.

  7. Valutare tutte le colonne espressioni, ma rimandare la verifica della presenza di vincoli su queste colonne.Evaluate all expression columns, but delay checking any constraints on these columns.

  8. Generare gli eventi ListChanged per gli oggetti DataView associati e gli eventi PropertyChanged per gli oggetti DataRowView associati interessati dalle valutazioni delle colonne espressioni.Raise ListChanged events for associated DataView objects and PropertyChanged events for associated DataRowView objects affected by the expression column evaluations.

  9. Generare gli eventi RowChanged o RowDeleted come applicabile.Raise RowChanged or RowDeleted events as applicable.

  10. Verificare i vincoli per le colonne espressioni.Check constraints on expression columns.

Nota

Le modifiche alle colonne espressioni non generano mai eventi DataTable,Changes to expression columns never raise DataTable events. ma generano solo eventi DataView e DataRowView,Changes to expression columns only raise DataView and DataRowView events. Le colonne espressioni possono avere dipendenze su molte altre colonne e possono essere valutate più volte durante una singola operazione DataRow.Expression columns can have dependencies on multiple other columns, and can be evaluated multiple times during a single DataRow operation. Ogni valutazione di espressione genera eventi e una singola operazione DataRow può generare più eventi ListChanged e PropertyChanged quando sono interessate colonne espressioni, magari con più eventi per la stessa colonna espressioni.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.

Avviso

Non generare un'eccezione NullReferenceException all'interno del gestore eventi RowChanged.Do not throw a NullReferenceException within the RowChanged event handler. Se viene generata un'eccezione NullReferenceException all'interno dell'evento RowChanged di un oggetto DataTable, allora il DataTable sarà danneggiato.If a NullReferenceException is thrown within the RowChanged event of a DataTable, then the DataTable will be corrupted.

EsempioExample

Nell'esempio seguente viene illustrato come creare gestori per gli eventi RowChanged, RowChanging, RowDeleted, RowDeleting, ColumnChanged, ColumnChanging, TableNewRow, TableCleared e TableClearing.The following example demonstrates how to create event handlers for the RowChanged, RowChanging, RowDeleted, RowDeleting, ColumnChanged, ColumnChanging, TableNewRow, TableCleared, and TableClearing events. Ogni gestore evento visualizza l'output nella finestra della console quando viene attivato.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

Vedere ancheSee also