c# - 如何在 C# 中取消 CellEnter/CellLeave 事件?

标签 c# events datagridview

我有 DataGridView。在某些单元格中,我添加了一些数据。如果我当前正在编辑的单元格是空的并且我要离开它,则会向用户显示一条消息“bla-bla-bla”,并且处于编辑模式的单元格必须重新获得焦点。

为此,我使用了 CellEnterCellLeaveCellEndEdit 等,我想在检查输入的值后取消这些事件细胞。但我是菜鸟,它不起作用。请帮我。很高兴看到任何建议。

这是我的代码的一个变体。我尝试了其他事件,但它非常天真

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1[e.ColumnIndex, e.RowIndex] == null)
    {
        MessageBox.Show("Empty cell!");

        dataGridView1.CurrentCell = dataGridView1[e.ColumnIndex, e.RowIndex];
    }
}

最佳答案

我认为您必须寻找基于DataGridViewCellValidating 事件的解决方案。

它在 DataGridView 即将离开编辑模式时触发,允许您不接受用户输入的值。要拒绝输入的值,在事件处理程序的代码中,您必须将 e.Cancel 设置为 True

private void dataGridView1_CellValidating(object sender,
    DataGridViewCellValidatingEventArgs e)
{

    if (!IsValueValid(e.FormattedValue))
    {
        e.Cancel = true;

        MessageBox.Show("Not Valid!");
    }
}

网上有很多例子,可以直接在MSDNDataGridViewCellValidatingEventArgs的文档中找到一个. 另请查看属性文档 DataGridViewCellValidatingEventArgs.FormattedValue

注意 IsValueValid(Object o) 方法不是 DataGridView 组件的一部分,只是一个命名示例,您应该在代码中声明它并提供一个验证正文。

关于c# - 如何在 C# 中取消 CellEnter/CellLeave 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11297232/

相关文章:

c# - 如何确定用户单击了 DataGridView 而不是 Cell

c# - NAudio 缓冲区已满异常

javascript - 事件监听器与事件处理程序

c# - 消失的代码?

c# - .NET : Is creating new EventArgs every time the event fires a good practice?

vb.net - CellEndEdit 之后的 DataGridView SetFocus

c# - 委托(delegate)不只是简写接口(interface)吗?

c# - 如何处理大量的静态变量和集合?

c# - 如何在 Lua 中注册 C# 类构造函数

c# - DatagridView 单元格绘画无法正常工作