【问题标题】:Cancel cell validation AND exit editing mode取消单元格验证并退出编辑模式
【发布时间】:2015-10-09 10:07:50
【问题描述】:

我的目标是在我的 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;
    }

}

如何继续使单元格恢复其原始值而不需要我跟踪该值?

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    您可以使用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,您将其设置在两个不同的位置,但您从不检查。这只是您的代码特有的东西的残余,还是您打算以某种方式展示它如何成为整体解决方案的一部分?
    • @TomBogle 好吧...那是一段时间了,我不记得这样做的确切原因。但是,通过查看 cmets/code,这个想法似乎很清楚。我想我没有包含它以尊重 OP 的原始代码,并且因为处理 isValid 的部分也没有显示。这不完全是一个直接工作的算法,而几乎是一个伪算法。无论如何,我已经用更正更新了代码。谢谢你告诉我。
    猜你喜欢
    • 2020-12-06
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    相关资源
    最近更新 更多