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

我有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即将离开编辑模式并允许您不接受用户输入的值时,它会被触发。 要拒绝输入的值,请在event-handler的代码中将e.Cancel设置为True

 private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (!IsValueValid(e.FormattedValue)) { e.Cancel = true; MessageBox.Show("Not Valid!"); } } 

Web中有许多示例,可以直接在MSDN中的DataGridViewCellValidatingEventArgs文档中找到。 另请参阅属性DataGridViewCellValidatingEventArgs.FormattedValue的文档

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

无法为某些单元格或行禁用DataGrids CellEnter CellLeave事件。

你可以做的是存储一个列表<>的单元格,这些单元格为空/不应该调用进入/离开事件,在进行CellEnter / CellLeave之前,检查单元格是否在禁用单元格列表中。