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

DataGridView1.CurrentCell and BeginEdit doesn't work if I move with Tab

C#、WinForms。

也许这是一个愚蠢而琐碎的问题,但我无法摆脱! 我有一个包含 4 列的 DataGridView1。我检查第 1 列中每一行的值是否与第 2 列中前一行的值相同。如果是,MessageBox 似乎会通知我......我想将焦点放在刚刚输入双精度值的单元格。因此我写了这段代码:

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;
            }
        }
    }
}

并且 CurrentCell 工作正常。问题是这种控制是通过 CellEndEdit 事件执行的,当我按下 Tab 键移动到下一个单元格时(或者我用鼠标单击到下一个单元格),因此,即使如果 BeginEdit 将我放在右边的单元格上让我编辑值,只要我再次按 Tab 键,它就会将更改后的值移到下一个单元格中。似乎在显示 MessageBox 之前按下的 Tab 仍保留在内存中。

当我写一个双精度值时,出现 MessageBox

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

活动结束时

知道如何处理这个问题吗?

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

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