Handle DataGridView errors in C#

Handle DataGridView errors

This example shows how you can handle DataGridView errors when you modify the data in the DataGridView control. The example Build a DataTable and bind it to a DataGridView in C# shows how to use a DataGridView control to display the data in a DataTable created in code.

The DataTable ensures that its data meets its restrictions. 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 displays an ugly dialog that describes the error and includes a sack trace.

If you don’t want to display the default dialog, you can catch the DataGridView control’s DataError event. Your code can try to figure out what it wrong, or at least tell the user that the data is invalid in more friendly terms.

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;

    // Display an error message.
    string txt = "Error with " +
        dgvPeople.Columns[e.ColumnIndex].HeaderText +
        "\n\n" + e.Exception.Message;
    MessageBox.Show(txt, "Error",
        MessageBoxButtons.OK, MessageBoxIcon.Error);

    // 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, and that 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.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls, database and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Handle DataGridView errors in C#

  1. ali hatem says:
    //extra : more customized to replace the
    // system error text & in any language 
    var exType = e.Exception.GetType().ToString();
    			
    if (exType == "System.FormatException") {
        MessageBox.Show("any text in any language",
        "Error in any language",
        MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *