Windows forms datagridview dataerror

Практическое руководство. Обработка ошибок, связанных с вводом данных с помощью элемента управления DataGridView, в Windows Forms How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView Control

В примере кода ниже показано, как использовать элемент управления DataGridView для сообщения пользователю об ошибках ввода данных. The following code example demonstrates how to use the DataGridView control to report data entry errors to the user.

Пример Example

Компиляция кода Compiling the Code

Для этого примера требуются: This example requires:

  • ссылки на сборки System, System.Data, System.Windows.Forms и System.XML. References to the System, System.Data, System.Windows.Forms, and System.XML assemblies.

Безопасность платформы .NET Framework .NET Framework Security

Хранение конфиденциальных сведений (например, пароля) в строке подключения может повлиять на безопасность приложения. Storing sensitive information, such as a password, within the connection string can affect the security of your application. Использование проверки подлинности Windows (также называемой встроенными средствами безопасности) — более безопасный способ управления доступом к базе данных. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. Дополнительные сведения см. в разделе Защита сведений о подключении. For more information, see Protecting Connection Information.

Data Grid View Data Error Contexts Перечисление

Определение

Представляет состояние привязанного к данным элемента управления DataGridView при ошибке. Represents the state of a data-bound DataGridView control when a data error occurred.

Это перечисление имеет атрибут FlagsAttribute, который разрешает побитовое сочетание значений его элементов.

Произошла ошибка в данных при копировании содержимого в буфер обмена. A data error occurred when copying content to the Clipboard. Данное значение указывает на то, что не удалось преобразовать значение ячейки в строку. This value indicates that the cell value could not be converted to a string.

Произошла ошибка в данных при фиксации изменений в хранилище данных. A data error occurred when committing changes to the data store. Данное значение указывает на то, что введенные в ячейку данные не удалось зафиксировать в соответствующем хранилище данных. This value indicates that data entered in a cell could not be committed to the underlying data store.

Произошла ошибка в данных при перемещении курсора выделения на другую ячейку. A data error occurred when the selection cursor moved to another cell. Данное значение указывает на то, что пользователь выбрал ячейку при наличии нештатной ситуации в ранее выбранной ячейке. This value indicates that a user selected a cell when the previously selected cell had an error condition.

Произошла ошибка в данных при выводе на экран ячейки, которая была заполнена источником данных. A data error occurred when displaying a cell that was populated by a data source. Данное значение указывает на то, что в ячейке не может быть отображено значение из источника данных, или же на то, что преобразования значения из источника данных не происходит. This value indicates that the value from the data source cannot be displayed by the cell, or a mapping that translates the value from the data source to the cell is missing.

Читайте также:  Как повысить качество скриншота экрана windows 10

Произошла ошибка в данных при попытке форматирования данных, отправка которых в хранилище данных или загрузка которых из хранилища данных производится в данный момент. A data error occurred when trying to format data that is either being sent to a data store, or being loaded from a data store. Данное значение указывает на то, что не удалось изменить ячейку ввиду неправильности форматирования. This value indicates that a change to a cell failed to format correctly. Необходимо либо исправить новое значение ячейки, либо изменить форматирование ячейки. Either the new cell value needs to be corrected or the cell’s formatting needs to change.

Произошла ошибка в данных при восстановлении предыдущего значения ячейки. A data error occurred when restoring a cell to its previous value. Значение указывает на попытку ячейки отменить правку и сбой при откате к начальному значению. This value indicates that a cell tried to cancel an edit and the rollback to the initial value failed. Такое может происходить, если форматирование ячейки было изменено и оказалось несовместимым с начальным значением. This can occur if the cell formatting changed so that it is incompatible with the initial value.

Произошла ошибка в данных при потере фокуса элементом управления DataGridView. A data error occurred when the DataGridView lost focus. Значение указывает на то, что после потери фокуса элементом управления DataGridView не удалось зафиксировать пользовательские изменения. This value indicates that the DataGridView could not commit user changes after losing focus.

Произошла ошибка в данных при анализе новых данных. A data error occurred when parsing new data. Данное значение указывает на то, что элементу управления DataGridView не удалось проанализировать новые данные, введенные пользователем или загруженные из соответствующего хранилища данных. This value indicates that the DataGridView could not parse new data that was entered by the user or loaded from the underlying data store.

Произошла ошибка в данных при вычислении оптимального размера ячейки. A data error occurred when calculating the preferred size of a cell. Данное значение указывает на то, что элементу управления DataGridView не удалось вычислить оптимальную ширину или высоту ячейки при программно реализованном изменении размера столбца или строки. This value indicates that the DataGridView failed to calculate the preferred width or height of a cell when programmatically resizing a column or row. Такое может происходить при неудачной попытке форматирования значения в ячейке. This can occur if the cell failed to format its value.

Произошла ошибка в данных при удалении строки. A data error occurred when deleting a row. Данное значение указывает на то, что соответствующее хранилище данных сгенерировало исключение при удалении строки в привязанном к данным элементе управления DataGridView. This value indicates that the underlying data store threw an exception when a data-bound DataGridView deleted a row.

Произошла ошибка в данных при просмотре новой области прокрутки. A data error occurred when scrolling a new region into view. Данное значение указывает на то, что при прокрутке, выполняемой программно или при помощи полосы прокрутки, предпринята попытка просмотра ячейки с ошибками в данных. This value indicates that a cell with data errors scrolled into view programmatically or with the scroll bar.

Примеры

В следующем примере кода показано использование этого типа. The following code example illustrates the use of this type. Этот пример является частью большого примера, который можно найти в разделе как управлять ошибками, происходящими при вводе данных в элементе управления Windows Forms DataGridView. This example is part of a larger example available in How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView Control.

Читайте также:  Записки windows 10 что это такое

Комментарии

Члены этого перечисления можно комбинировать с помощью побитовой операции или для представления состояния привязанных к данным данных при возникновении DataGridView ошибки данных. Members of this enumeration may be combined using the bitwise OR operation to represent the state of a data-bound DataGridView when a data error occurred. Например, если пользователь вводит недопустимое значение ячейки (например, вводит имя в ячейку, которая ожидает дату), а затем выбирает другую ячейку, DataGridView будет предпринята попытка зафиксировать недопустимое значение ячейки. For example, if a user enters an invalid cell value (such as entering a name in a cell that expects a date) and then selects a different cell, the DataGridView will try to commit the invalid cell value. При сбое фиксации DataGridView вызывает DataError событие, Context свойство которого будет иметь значение Commit и куррентцеллчанже. When the commit fails, the DataGridView will raise a DataError event whose Context property will have a value of Commit and CurrentCellChange.

Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control

Handling errors from the underlying data store is a required feature for a data-entry application. The Windows Forms DataGridView control makes this easy by exposing the DataError event, which is raised when the data store detects a constraint violation or a broken business rule.

In this walkthrough, you will retrieve rows from the Customers table in the Northwind sample database and display them in a DataGridView control. When a duplicate CustomerID value is detected in a new row or an edited existing row, the DataError event will occur, which will be handled by displaying a MessageBox that describes the exception.

Prerequisites

In order to complete this walkthrough, you will need:

  • Access to a server that has the Northwind SQL Server sample database.

Creating the Form

To handle data-entry errors in the DataGridView control

Create a class that derives from Form and contains a DataGridView control and a BindingSource component.

The following code example provides basic initialization and includes a Main method.

Implement a method in your form’s class definition for handling the details of connecting to the database.

This code example uses a GetData method that returns a populated DataTable object. Be sure that you set the connectionString variable to a value that is appropriate for your database.

Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see Protecting Connection Information.

Implement a handler for your form’s Load event that initializes the DataGridView and BindingSource and sets up the data binding.

Handle the DataError event on the DataGridView.

If the context for the error is a commit operation, display the error in a MessageBox.

Testing the Application

You can now test the form to make sure it behaves as expected.

To test the form

Press F5 to run the application.

You will see a DataGridView control filled with data from the Customers table. If you enter a duplicate value for CustomerID and commit the edit, the cell value will revert automatically and you will see a MessageBox that displays the data entry error.

Next Steps

This application gives you a basic understanding of the DataGridView control’s capabilities. You can customize the appearance and behavior of the DataGridView control in several ways:

Handle very large data sets using virtual mode. For more information, see Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control.

Читайте также:  Secret net обновление windows

Data Grid View. Data Error Событие

Определение

Происходит, когда внешний анализ данных или операция проверки вызывают исключение или когда попытка зафиксировать данные в источнике данных приводит к сбою. Occurs when an external data-parsing or validation operation throws an exception, or when an attempt to commit data to a data source fails.

Тип события

Примеры

В следующем примере кода демонстрируется DataError обработчик событий. The following code example demonstrates a DataError event handler. Этот пример является частью большого примера, доступного в DataGridViewComboBoxColumn разделе Обзор класса. This example is part of a larger example available in the DataGridViewComboBoxColumn class overview topic.

Комментарии

Это DataError событие позволяет обрабатывать исключения, возникающие в коде, который вызывается элементом управления во время операций обработки данных. The DataError event enables you to handle exceptions thrown in code that is called by the control during data processing operations.

Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about how to handle events, see Handling and Raising Events.

ColumnIndexСвойства и RowIndex DataGridViewDataErrorEventArgs объекта, связанного с этим событием, обычно указывают на ячейку, в которой произошла ошибка данных. The ColumnIndex and RowIndex properties of the DataGridViewDataErrorEventArgs object associated with this event normally indicate the cell in which the data error occurred. Однако при возникновении ошибки во внешнем источнике данных источник данных может не предоставить столбец, в котором произошла ошибка. When the error occurs in an external data source, however, the data source may not provide the column in which the error occurred. В этом случае ColumnIndex свойство обычно указывает столбец текущей ячейки на момент возникновения ошибки. In this case, the ColumnIndex property typically indicates the column of the current cell at the time of the error.

Data Grid View. Data Error Событие

Определение

Происходит, когда внешний анализ данных или операция проверки вызывают исключение или когда попытка зафиксировать данные в источнике данных приводит к сбою. Occurs when an external data-parsing or validation operation throws an exception, or when an attempt to commit data to a data source fails.

Тип события

Примеры

В следующем примере кода демонстрируется DataError обработчик событий. The following code example demonstrates a DataError event handler. Этот пример является частью большого примера, доступного в DataGridViewComboBoxColumn разделе Обзор класса. This example is part of a larger example available in the DataGridViewComboBoxColumn class overview topic.

Комментарии

Это DataError событие позволяет обрабатывать исключения, возникающие в коде, который вызывается элементом управления во время операций обработки данных. The DataError event enables you to handle exceptions thrown in code that is called by the control during data processing operations.

Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about how to handle events, see Handling and Raising Events.

ColumnIndexСвойства и RowIndex DataGridViewDataErrorEventArgs объекта, связанного с этим событием, обычно указывают на ячейку, в которой произошла ошибка данных. The ColumnIndex and RowIndex properties of the DataGridViewDataErrorEventArgs object associated with this event normally indicate the cell in which the data error occurred. Однако при возникновении ошибки во внешнем источнике данных источник данных может не предоставить столбец, в котором произошла ошибка. When the error occurs in an external data source, however, the data source may not provide the column in which the error occurred. В этом случае ColumnIndex свойство обычно указывает столбец текущей ячейки на момент возникновения ошибки. In this case, the ColumnIndex property typically indicates the column of the current cell at the time of the error.

Оцените статью