We can catch data errors before they hit the database by handling the CellValidating event.
We need to clean up row errors that might have been placed during the CellValidating event if the edit is successful or cancelled. That is done in the CellEndEdit event.
A variety of errors are caught and handed to the user as DataError events. You can handle this event and take appropriate action. The DataGridViewDataErrorEventArgs object has the Exception, the row and column indexes and a context. The context is from the DataGridViewDataErrorContexts enumeration with possible values:
| Member name | Description |
|---|---|
| ClipboardContent | A data error occurred when copying content to the Clipboard. This value indicates that the cell value could not be converted to a string. |
| Commit | 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. |
| CurrentCellChange | 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. |
| Display | 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. |
| Formatting | 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. |
| InitialValueRestoration | 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. |
| LeaveControl | A data error occurred when the DataGridView lost focus. This value indicates that the DataGridView could not commit user changes after losing focus. |
| Parsing | A data error occurred when parsing new data. This value indicates that the DataGridView could not parse new data that was entered by the user or loaded from the underlying data store. |
| PreferredSize | A data error occurred when calculating the preferred size of a cell. 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. |
| RowDeletion | A data error occurred when deleting a row. This value indicates that the underlying data store threw an exception when a data-bound DataGridView deleted a row. |
| Scroll | 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. |
Look at project DGV\Validating. Here is the code we threw in:
private void studentDataGridView_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
string colName = studentDataGridView.Columns[e.ColumnIndex].Name;
switch (colName)
{
case "FirstName":
case "LastName":
if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
{
studentDataGridView.Rows[e.RowIndex].ErrorText
= colName + " must not be empty.";
e.Cancel = true;
}
break;
case "Age":
{
try
{
int age = Convert.ToInt32(e.FormattedValue);
if (age < 0 || age > 150)
{
studentDataGridView.Rows[e.RowIndex].ErrorText
= "Age must be between 0 and 150.";
e.Cancel = true;
}
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
}
break;
}
}
private void studentDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
studentDataGridView.Rows[e.RowIndex].ErrorText = String.Empty;
}
private void studentDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Data Error: {0}: {1} ", e.Exception.GetType(), e.Exception.Message);
sb.AppendLine();
sb.AppendFormat("Context: {0}", e.Context);
sb.AppendLine();
sb.AppendFormat("Column: {0} {1}", e.ColumnIndex,
studentDataGridView.Columns[e.ColumnIndex].Name);
MessageBox.Show(sb.ToString(), "Data error");
}