BLOG.CSHARPHELPER.COM: Handle errors when a DataGridView modifies data in C#
Handle errors when a DataGridView modifies data in C#
The example Make a DataTable in code and bind it to a DataGridView control in C# shows how to use a DataGridView control display the data in a DataTable created by code. The DataTable ensures that its data meets its requirements. For example, the DataTable won't let the program add a record to the data that is missing a required field or that is the wrong data type.
If the DataTable is associated with a DataGridView and the user tries to enter invalid data, the DataGridView raises a DataError event. Your code can catch the event and try to figure out what it wrong, or at least tell the user that the data is invalid.
This example uses the following DataError event handler to tell the user when a problem occurs.
// An error in the data occurred. private void dgvPeople_DataError(object sender, DataGridViewDataErrorEventArgs e) { // Don't throw an exception when we're done. e.ThrowException = false;
// If this is true, then the user is trapped in this cell. e.Cancel = false; }
This code simply displays a message telling the user which column had the error and what the exception was. It also sets e.Cancel to false to allow the event to continue to propagate, which ends the change. If you don't do this, then focus remains in the cell that has the error and the user must fix it before moving to a new cell.
Comments