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

时间:2014-10-23 07:09:23

标签: c# datagridview invalidoperationexception

我有一个从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;
}

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

  

未处理的类型&#34; System.InvalidOperationException&#34;在   System.Windows.Forms.dll中

     

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

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

2 个答案:

答案 0 :(得分:17)

此错误是由

引起的
  

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

作为接受的答案in this post

修复程序(我已经过验证):使用BeginInvoke来调用moveRowTo

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

BeginInvoke是异步调用,因此dataGridView2_CellEndEdit会立即返回,之后执行moveRowTo方法,此时dataGridView2不再使用当前有效细胞。

答案 1 :(得分:-1)

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