如果我使用 Tab 移动,DataGridView1.CurrentCell 和 BeginEdit 不起作用

Wic*_*cio 3 c# datagridview cells winforms

C#、WinForms。

也许这是一个愚蠢而微不足道的问题,但我无法摆脱!我有DataGridView14 列。我检查第 1 列中每一行的值是否与第 2 列中前一行的值相同。如果是,MessageBox则会出现 a 通知我...并且我想将焦点移至其中存在的单元格是刚刚输入的双精度值。因此我写了这段代码:

private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs cella)
{
    if (cella.RowIndex > 0 && cella.ColumnIndex == 1)
    {
        var PrevCell = DataGridView1.Rows[cella.RowIndex - 1].Cells[2].Value.ToString();
        if (DataGridView1.Rows[cella.RowIndex].Cells[cella.ColumnIndex].Value.ToString() == PrevCell)
        {
            MessageBox.Show("Amount already exists. Change the current value or the previous occurrence", "Double value, already inserted", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            DataGridView1.CurrentCell = DataGridView1.Rows[cella.RowIndex].Cells[cella.ColumnIndex];
            DataGridView1.BeginEdit(true);
            //only a test:
            //return;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

而且CurrentCell效果很好。问题是,CellEndEdit当我按下Tab按键移动到下一个单元格(或者用鼠标单击到下一个单元格)时,这种控制是通过事件执行的,因此,即使将BeginEdit我放在正确的单元格上,当我编辑该值时,一旦再次按 Tab,它就会将更改后的值移动到下一个单元格中。看来在显示 MessageBox 之前按下的 Tab 仍然保留在内存中。

当我写入双精度值时,会出现 MessageBox 当我写入双精度值时,会出现 MessageBox

当 CurrentCell 和 BeginEdit 引导我在正确的单元格中更改双精度值时 当 CurrentCell 和 BeginEdit 引导我在正确的单元格中更改双精度值时

活动结束时

活动结束时

关于如何处理这个问题有什么想法吗?

Lar*_*ech 5

您需要选择单元格并在CellEndEdit 事件发生调用 BeginEdit 方法。为此,请将该代码包装在 BeginInvoke 块中:

this.BeginInvoke(new Action(() => {
  DataGridView1.CurrentCell = DataGridView1.Rows[cella.RowIndex].Cells[cella.ColumnIndex];
  DataGridView1.BeginEdit(true);
}));
Run Code Online (Sandbox Code Playgroud)