无法验证,但无法在DataGridView中删除

Mal*_*ist 4 c# datagridview

这是在我的DataGridView的RowValidation函数中:

        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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

但是,有一个问题,如果用户说不,意味着他或她没有纠正这一行,我不能像我尝试那样删除它.我得到异常:InvalidOperationException:无法在此事件处理程序中执行操作

我怎样才能纠正这个并仍然删除该行?

SLa*_*aks 11

要删除处理程序外部的行,可以调用BeginInvoke:

BeginInvoke(new Action(delegate { viewApplications.Rows.RemoveAt(e.RowIndex); }));
Run Code Online (Sandbox Code Playgroud)

这将在下一个消息循环期间运行委托中的代码.