Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failure to validate, but cannot remove in DataGridView

This is in my RowValidation function of DataGridView:

        DataGridViewRow row = viewApplications.Rows[e.RowIndex];
        if (row.Cells[colApplyTo.Index].Value == (object)-1) {
            if (MessageBox.Show("Row #" + (e.RowIndex + 1) + " is not assigned to a charge. Would you like to correct this? (If no, the row will be deleted)", "Invalid Row", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) {
                viewApplications.Rows.RemoveAt(e.RowIndex);
            } else {
                e.Cancel = true;
            }
        }

However, there is a problem, if the user says no, meaning he or she does not with to correct this row, I cannot delete it like I try to do. I get the exception: InvalidOperationException: Operation cannot be performed in this event handler

How can I correct this and still remove the row?

like image 392
Malfist Avatar asked Dec 22 '22 03:12

Malfist


1 Answers

To remove the row outside the handler, you can call BeginInvoke:

BeginInvoke(new Action(delegate { viewApplications.Rows.RemoveAt(e.RowIndex); }));

This will run the code in the delegate during the next message loop.

like image 58
SLaks Avatar answered Dec 31 '22 14:12

SLaks