如何逃避对setCurrentCellAddressCore的重入调用?

我有一个从cell_endedit调用的函数。 它在dataGridView中移动dataGridViewRow:

private void moveRowTo(DataGridView table, int oldIndex, int newIndex) { if (newIndex < oldIndex) { oldIndex += 1; } else if (newIndex == oldIndex) { return; } table.Rows.Insert(newIndex, 1); DataGridViewRow row = table.Rows[newIndex]; DataGridViewCell cell0 = table.Rows[oldIndex].Cells[0]; DataGridViewCell cell1 = table.Rows[oldIndex].Cells[1]; row.Cells[0].Value = cell0.Value; row.Cells[1].Value = cell1.Value; table.Rows[oldIndex].Visible = false; table.Rows.RemoveAt(oldIndex); table.Rows[oldIndex].Selected = false; table.Rows[newIndex].Selected = true; } 

在row table.Rows.Insert(newIndex,1)我收到以下错误:

System.Windows.Forms.dll中类型为“System.InvalidOperationException”的未处理exception

附加数据:操作无效,因为它导致对SetCurrentCellAddressCore函数的可重入调用。

当我在编辑当前单元格时单击另一个单元格时会发生这种情况。 如何规避此类错误并正确插入行?

此错误是由

在DataGridView仍在使用它时导致活动单元格被更改的任何操作

作为这篇文章中接受的答案。

修复(我已经validation):使用BeginInvoke调用moveRowTo

 private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e) { this.BeginInvoke(new MethodInvoker(() => { moveRowTo(dataGridView2, 0, 1); })); } 

BeginInvoke是一个异步调用,因此dataGridView2_CellEndEdit立即返回,之后执行moveRowTo方法,此时dataGridView2不再使用当前活动的单元格。

 if ( (datagridview.SelectedCells[0].RowIndex != datagridview.CurrentCell.RowIndex) || (datagridview.SelectedCells[0].ColumnIndex!= datagridview.CurrentCell.ColumnIndex) ) { return; }