David Perry
David Perry

Reputation: 1364

Cell validation in DataGridView preventing Cancel button from firing

I've got a DataGridView with a couple columns I'm doing null validation against, as follows:

dgv.RowValidating += DisallowNulls;

private void DisallowNulls(object sender, DataGridViewCellCancelEventArgs e)
{
    if (dgv.Rows[e.RowIndex].Cells[0].Value == DBNull.Value || dgv.Rows[e.RowIndex].Cells[1].Value == DBNull.Value )
    {
        dgv.Rows[e.RowIndex].ErrorText = "Cells may not be empty";
        e.Cancel = true;
    }
}

This DataGridView exists as part of an entry form with a Cancel button. In the event that the Cancel button is clicked, I would like to cancel any pending edits to the DGV, reject all changes to its underlying DataTable, etc. Unfortunately, this seems to fail if the user has entered invalid data or simply partially entered a row in any way that fails validation. Cancel only works if all form data is valid, which is obviously problematic.

So I jump into my Cancel button's code and try to bypass validation. I play with EndEdit, CancelEdit, CausesValidation, etc to no avail, and after a quick trace I see why none of it worked - the validation handler is making my code unreachable.

My problem is that the RowValidating event seems to fire BEFORE my button's click handler is fired, and e.Cancel = true appears to end execution for both handlers. In any case, clicking cancel fires dgv.RowValidating and never reaches button.Click at all. I also don't see any way to discern from sender/EventArgs that my button click triggered validation, so I'm not sure how to discriminate...

So how do I either a) get my button's code to fire before validation or b) determine that the validation was triggered by the button click and bypass it?

Or am I doing something else wrong entirely?

Upvotes: 2

Views: 2716

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

Set CausesValidation property of your cancel Button to false and then call CancelEdit method of your DataGridView in Click event handler of your cancel button:

private void button1_Click(object sender, EventArgs e)
{
    this.dataGridView1.CancelEdit();
}

Setting CausesValidation for your button, prevents from raising validation events when you click on your button. Then by calling CancelEdit of your DataGridView you cancel pending changes of current editing cell.

Also setting AutoValidate property of your form to EnableAllowFocusChange, lets you to change the focus from invalid editing control (and thus click on the cancel button).

Upvotes: 2

Related Questions