DataTable 이벤트 처리Handling DataTable Events

DataTable 개체는 애플리케이션에서 처리할 수 있는 일련의 이벤트를 제공합니다.The DataTable object provides a series of events that can be processed by an application. 다음 표에서는 DataTable 이벤트에 대해 설명합니다.The following table describes DataTable events.

이벤트Event 설명Description
Initialized EndInitDataTable 메서드가 호출된 후에 발생합니다.Occurs after the EndInit method of a DataTable is called. 이 이벤트는 기본적으로 디자인 타임 시나리오를 지원하는 데 사용됩니다.This event is intended primarily to support design-time scenarios.
ColumnChanged DataColumn에서 값이 성공적으로 변경된 후에 발생합니다.Occurs after a value has been successfully changed in a DataColumn.
ColumnChanging DataColumn의 값이 제출될 때 발생합니다.Occurs when a value has been submitted for a DataColumn.
RowChanged DataColumn 값 또는 RowState에 있는 DataRowDataTable가 성공적으로 변경된 후에 발생합니다.Occurs after a DataColumn value or the RowState of a DataRow in the DataTable has been changed successfully.
RowChanging DataColumn 값 또는 RowState에 있는 DataRowDataTable에 대한 변경된 값이 제출될 때 발생합니다.Occurs when a change has been submitted for a DataColumn value or the RowState of a DataRow in the DataTable.
RowDeleted DataRowDataTableDeleted로 표시된 후에 발생합니다.Occurs after a DataRow in the DataTable has been marked as Deleted.
RowDeleting DataRowDataTableDeleted로 표시되기 전에 발생합니다.Occurs before a DataRow in the DataTable is marked as Deleted.
TableCleared ClearDataTable 메서드 호출을 통해 모든 DataRow가 성공적으로 삭제된 후에 발생합니다.Occurs after a call to the Clear method of the DataTable has successfully cleared every DataRow.
TableClearing Clear 메서드가 호출된 후 Clear 작업이 시작되기 전에 발생합니다.Occurs after the Clear method is called but before the Clear operation begins.
TableNewRow DataRowNewRow 메서드 호출을 통해 새 DataTable가 만들어진 후에 발생합니다.Occurs after a new DataRow is created by a call to the NewRow method of the DataTable.
Disposed DataTableDisposed가 될 때 발생합니다.Occurs when the DataTable is Disposed. MarshalByValueComponent에서 상속됩니다.Inherited from MarshalByValueComponent.

참고

행을 추가하거나 삭제하는 대부분의 작업은 ColumnChangedColumnChanging 이벤트를 발생시키지 않습니다.Most operations that add or delete rows do not raise the ColumnChanged and ColumnChanging events. 그러나 ReadXml 메서드는 ColumnChangedColumnChanging 이벤트를 발생시킵니다. 단, 읽고 있는 XML 문서가 XmlReadMode이고 DiffGramAuto 또는 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.

경고

DataSet 이벤트가 발생한 RowChanged에서 데이터를 수정하면 데이터가 손상될 수 있습니다.Data corruption can occur if data is modified in a DataSet from which the RowChanged event is raised. 이와 같은 데이터 손상이 발생하면 예외가 발생하지 않습니다.No exception will be raised if such data corruption occurs.

Constraints 속성은 ConstraintCollection 인스턴스를 포함합니다.The Constraints property holds a ConstraintCollection instance. ConstraintCollection 클래스는 CollectionChanged 이벤트를 노출합니다.The ConstraintCollection class exposes a CollectionChanged event. 이 이벤트는 ConstraintCollection에서 제약 조건이 추가되거나 수정되거나 제거될 때 발생합니다.This event fires when a constraint is added, modified, or removed from the ConstraintCollection.

Columns 속성은 DataColumnCollection 인스턴스를 포함합니다.The Columns property holds a DataColumnCollection instance. DataColumnCollection 클래스는 CollectionChanged 이벤트를 노출합니다.The DataColumnCollection class exposes a CollectionChanged event. 이 이벤트는 DataColumn에서 DataColumnCollection이 추가되거나 수정되거나 제거될 때 발생합니다.This event fires when a DataColumn is added, modified, or removed from the DataColumnCollection. 열의 이름, 형식, 식 또는 위치 등이 변경되어 열이 수정되면 이 이벤트가 발생합니다.Modifications that cause the event to fire include changes to the name, type, expression or ordinal position of a column.

TablesDataSet 속성은 DataTableCollection 인스턴스를 포함합니다.The Tables property of a DataSet holds a DataTableCollection instance. DataTableCollection 클래스는 CollectionChangedCollectionChanging 이벤트를 모두 노출합니다.The DataTableCollection class exposes both a CollectionChanged and a CollectionChanging event. 이 두 이벤트는 DataTable에서 DataSet이 추가되거나 제거될 때 발생합니다.These events fire when a DataTable is added to or removed from the DataSet.

DataRows가 변경되는 경우에도 관련 DataView의 이벤트가 발생합니다.Changes to DataRows can also trigger events for an associated DataView. DataView 클래스는 ListChanged 값이 변경되거나 뷰의 구성 또는 정렬 순서가 변경될 때 발생하는 DataColumn 이벤트를 노출합니다.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. DataRowView 클래스는 관련 PropertyChanged 값이 변경될 때 발생하는 DataColumn 이벤트를 노출합니다.The DataRowView class exposes a PropertyChanged event that fires when an associated DataColumn value changes.

작업 순서Sequence of Operations

다음은 DataRow가 추가, 수정 또는 삭제되는 경우의 작업 순서입니다.Here is the sequence of operations that occur when a DataRow is added, modified, or deleted:

  1. 제안된 레코드를 만들고 변경 내용을 적용합니다.Create the proposed record and apply any changes.

  2. 식이 아닌 열의 제약 조건을 검사합니다.Check constraints for non-expression columns.

  3. 가능한 경우 RowChanging 또는 RowDeleting 이벤트를 발생시킵니다.Raise the RowChanging or RowDeleting events as applicable.

  4. 제안된 레코드를 현재 레코드로 설정합니다.Set the proposed record to be the current record.

  5. 관련된 인덱스를 업데이트합니다.Update any associated indexes.

  6. 관련 ListChanged 개체에 대해 DataView 이벤트를 발생시키고, 관련 PropertyChanged 개체에 대해 DataRowView 이벤트를 발생시킵니다.Raise ListChanged events for associated DataView objects and PropertyChanged events for associated DataRowView objects.

  7. 모든 식 열을 계산합니다. 단, 열의 제약 조건 검사는 지금 수행하지 않습니다.Evaluate all expression columns, but delay checking any constraints on these columns.

  8. 식 열 계산 결과에 영향을 받은 관련 ListChanged 개체에 대해 DataView 이벤트를 발생시키고, 관련 PropertyChanged 개체에 대해 DataRowView 이벤트를 발생시킵니다.Raise ListChanged events for associated DataView objects and PropertyChanged events for associated DataRowView objects affected by the expression column evaluations.

  9. 가능한 경우 RowChanged 또는 RowDeleted 이벤트를 발생시킵니다.Raise RowChanged or RowDeleted events as applicable.

  10. 식 열의 제약 조건을 검사합니다.Check constraints on expression columns.

참고

식 열이 변경되는 경우에는 DataTable 이벤트가 발생하지 않습니다.Changes to expression columns never raise DataTable events. 식 열이 변경되면 DataViewDataRowView 이벤트만 발생합니다.Changes to expression columns only raise DataView and DataRowView events. 식 열은 다른 여러 열에 종속될 수 있으므로 단일 DataRow 작업 중 여러 번 계산될 수 있습니다.Expression columns can have dependencies on multiple other columns, and can be evaluated multiple times during a single DataRow operation. 식을 계산할 때마다 이벤트가 발생합니다. 또한 식 열이 변경되는 경우 동일한 식 열에 대한 여러 이벤트를 포함하여 단일 DataRow 작업에서 여러 ListChangedPropertyChanged 이벤트가 발생할 수 있습니다.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.

경고

NullReferenceException 이벤트 처리기 내에서 RowChanged을 throw하지 마세요.Do not throw a NullReferenceException within the RowChanged event handler. NullReferenceExceptionRowChangedDataTable 이벤트 내에서 throw되면 DataTable이 손상됩니다.If a NullReferenceException is thrown within the RowChanged event of a DataTable, then the DataTable will be corrupted.

예제Example

다음 예제에서는 RowChanged, RowChanging, RowDeleted, RowDeleting, ColumnChanged, ColumnChanging, TableNewRow, TableClearedTableClearing 이벤트에 대한 이벤트 처리기를 만드는 방법을 보여 줍니다.The following example demonstrates how to create event handlers for the RowChanged, RowChanging, RowDeleted, RowDeleting, ColumnChanged, ColumnChanging, TableNewRow, TableCleared, and TableClearing events. 각 이벤트 처리기는 이벤트가 발생하면 콘솔 창에 해당 출력을 표시합니다.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

참고자료See also