取消单元格验证并退出编辑模式

4
我的目标是在我的DataGridView上拥有友好的验证流程。
当用户为某个单元格输入不正确的值时,我希望能够:
- 退出编辑模式 - 恢复修改(即从单元格中恢复原始值) - 显示错误消息
我目前正在使用CellValidating事件来防止单元格更新其值,但我无法退出编辑模式。然后,该单元格将等待正确的值,并且不会允许用户仅取消并恢复操作...
以下是验证方法的示例代码:
private void dataGridViewMsg_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    [...] // Here, treatment determines is the new cell value isValid or not

    if (!isValid)
    {
        MessageBox.Show("The value entered is incorrect.", "Modification aborted");
        e.Cancel = true;
        dataGridViewMsg[e.ColumnIndex, e.RowIndex].IsInEditMode = false; // Someway, what I would like to do
        return;
    }

}

我该如何操作才能使单元格恢复其原始值,而无需跟踪此值?

1个回答

8

您可以使用EndEdit()来获取您想要的内容。

无论如何,请注意最好确保取消仅在预期条件下发生;否则,代码可能会因为在许多不同的点自动调用此事件而被卡住。例如,为了验证用户通过单元格编辑编写的输入,您可以依赖以下方法:

    bool cancelIt = false;

    private void dataGridViewMsg_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        [...] // Here, treatment determines is the new cell value isValid or not

        if (cancelIt && !isValid)
        {
            MessageBox.Show("The value entered is incorrect.", "Modification aborted");
            e.Cancel = true;
            dataGridViewMsg.EndEdit();
            cancelIt = false;
        }
    }

    //CellBeginEdit event -> the user has edited the cell and the cancellation part 
    //can be executed without any problem
    private void dataGridViewMsg_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
        cancelIt = true;
    }

在你的例子中,你引入了一个名为cancelIt的变量,在两个不同的位置设置了它,但从未检查过。这只是你代码中特定部分的遗留物,还是你本意是要展示这是整体解决方案的一部分? - Tom Bogle
@TomBogle 嗯...那是一段时间以前的事了,我不记得当时采用这种方式的确切原因。但是,通过查看注释/代码,这个想法似乎很清楚。我猜我没有包含它是为了尊重OP的原始代码,并且因为负责isValid的部分也没有显示出来。这不是一个直接工作的算法,而几乎是一个伪算法。无论如何,我已经用修正更新了代码。谢谢你让我知道。 - varocarbas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接