DataGridViewDataErrorEventArgs Класс

Определение

Предоставляет данные о событии DataError.

public ref class DataGridViewDataErrorEventArgs : System::Windows::Forms::DataGridViewCellCancelEventArgs
public class DataGridViewDataErrorEventArgs : System.Windows.Forms.DataGridViewCellCancelEventArgs
type DataGridViewDataErrorEventArgs = class
    inherit DataGridViewCellCancelEventArgs
Public Class DataGridViewDataErrorEventArgs
Inherits DataGridViewCellCancelEventArgs
Наследование

Примеры

В следующем примере кода показано, как реагировать на сведения, предоставляемые классом DataGridViewDataErrorEventArgs . Этот пример является частью более крупного примера, доступного в DataGridViewComboBoxColumn разделе обзора класса.

private:
    void DataGridView1_DataError(Object^ sender, DataGridViewDataErrorEventArgs^ anError)
    {

        MessageBox::Show("Error happened " + anError->Context.ToString());

        if (anError->Context == DataGridViewDataErrorContexts::Commit)
        {
            MessageBox::Show("Commit error");
        }
        if (anError->Context == DataGridViewDataErrorContexts::CurrentCellChange)
        {
            MessageBox::Show("Cell change");
        }
        if (anError->Context == DataGridViewDataErrorContexts::Parsing)
        {
            MessageBox::Show("parsing error");
        }
        if (anError->Context == DataGridViewDataErrorContexts::LeaveControl)
        {
            MessageBox::Show("leave control error");
        }

        if (dynamic_cast<ConstraintException^>(anError->Exception) != nullptr)
        {
            DataGridView^ view = (DataGridView^)sender;
            view->Rows[anError->RowIndex]->ErrorText = "an error";
            view->Rows[anError->RowIndex]->Cells[anError->ColumnIndex]->ErrorText = "an error";

            anError->ThrowException = false;
        }
    }
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)
{

    MessageBox.Show("Error happened " + anError.Context.ToString());

    if (anError.Context == DataGridViewDataErrorContexts.Commit)
    {
        MessageBox.Show("Commit error");
    }
    if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange)
    {
        MessageBox.Show("Cell change");
    }
    if (anError.Context == DataGridViewDataErrorContexts.Parsing)
    {
        MessageBox.Show("parsing error");
    }
    if (anError.Context == DataGridViewDataErrorContexts.LeaveControl)
    {
        MessageBox.Show("leave control error");
    }

    if ((anError.Exception) is ConstraintException)
    {
        DataGridView view = (DataGridView)sender;
        view.Rows[anError.RowIndex].ErrorText = "an error";
        view.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error";

        anError.ThrowException = false;
    }
}
Private Sub DataGridView1_DataError(ByVal sender As Object, _
ByVal e As DataGridViewDataErrorEventArgs) _
Handles DataGridView1.DataError

    MessageBox.Show("Error happened " _
        & e.Context.ToString())

    If (e.Context = DataGridViewDataErrorContexts.Commit) _
        Then
        MessageBox.Show("Commit error")
    End If
    If (e.Context = DataGridViewDataErrorContexts _
        .CurrentCellChange) Then
        MessageBox.Show("Cell change")
    End If
    If (e.Context = DataGridViewDataErrorContexts.Parsing) _
        Then
        MessageBox.Show("parsing error")
    End If
    If (e.Context = _
        DataGridViewDataErrorContexts.LeaveControl) Then
        MessageBox.Show("leave control error")
    End If

    If (TypeOf (e.Exception) Is ConstraintException) Then
        Dim view As DataGridView = CType(sender, DataGridView)
        view.Rows(e.RowIndex).ErrorText = "an error"
        view.Rows(e.RowIndex).Cells(e.ColumnIndex) _
            .ErrorText = "an error"

        e.ThrowException = False
    End If
End Sub

Комментарии

DataError Обработка события позволяет обрабатывать исключения, создаваемые кодом, не входящим в ваш контроль (например, внешним источником данных). Используйте свойство , Context чтобы определить состояние объекта на DataGridView момент возникновения исключения. Используйте свойство для Exception получения данных исключения. Если вы хотите обработать исключение с помощью дополнительных обработчиков событий, задайте ThrowException для свойства значение true.

Свойства ColumnIndex и RowIndex обычно указывают ячейку, в которой произошла ошибка данных. Однако при возникновении ошибки во внешнем источнике данных источник данных может не предоставить столбец, в котором произошла ошибка. В этом случае ColumnIndex свойство обычно указывает столбец текущей ячейки во время ошибки.

Конструкторы

DataGridViewDataErrorEventArgs(Exception, Int32, Int32, DataGridViewDataErrorContexts)

Инициализирует новый экземпляр класса DataGridViewDataErrorEventArgs.

Свойства

Cancel

Возвращает или задает значение, показывающее, следует ли отменить событие.

(Унаследовано от CancelEventArgs)
ColumnIndex

Получает индекс столбца ячейки, для которой произошло событие.

(Унаследовано от DataGridViewCellCancelEventArgs)
Context

Получает сведения о состоянии объекта DataGridView во время возникновения ошибки.

Exception

Получает исключение, представляющее ошибку.

RowIndex

Получает индекс строки ячейки, для которой произошло событие.

(Унаследовано от DataGridViewCellCancelEventArgs)
ThrowException

Получает или задает значение, указывающее, следует ли создавать исключение после того делегат DataGridViewDataErrorEventHandler закончил его обработку.

Методы

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Применяется к

См. также раздел