如何在C#中取消CellEnter / CellLeave事件? [英] How to cancel CellEnter/CellLeave event in C#?

查看:1119
本文介绍了如何在C#中取消CellEnter / CellLeave事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 DataGridView 。在某些单元格中,我添加一些数据。如果我当前正在编辑的单元格是空的,我即将离开,则会向用户显示一条消息bla-bla-bla,编辑模式下的单元格必须收到重点。

I have DataGridView. In some cells I add some data. If the cell, that I'm currently editing, is empty and I'm about to leave it, a message "bla-bla-bla" is shown to the user and the cell in edition mode must receive the focus back.

为此,我使用 CellEnter CellLeave CellEndEdit 等等,我想在检查单元格中输入的值后取消这些事件。但是我没有,它不工作。请帮帮我。很高兴看到任何建议。

For doing this I'm using CellEnter, CellLeave, CellEndEdit etc. and I want cancel those events after checking the value entered in the cell. But Im noob and it doesn't work. Please, help me. Would be glad to see any advice.

这是我的代码的一个变种。我试过与其他事件,但它是非常天真

Here is a variant of my code. I tried with other events, but it is very naive.

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


推荐答案

认为您必须根据 DataGridView CellValidating 事件寻找解决方案。

I think you must look for a solution based on the CellValidating event of the DataGridView.

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

It is fired just when the DataGridView is about to leave the edition mode and allows you to not accept the value that has been entered by the user. To reject the value entered, in the code of the event-handler, you must set the e.Cancel to True.

private void dataGridView1_CellValidating(object sender,
    DataGridViewCellValidatingEventArgs e)
{

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

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

网络中有很多示例,可以在 DataGridViewCellValidatingEventArgs 的文档中直接找到.aspx> MSDN 同时查看属性的文档 DataGridViewCellValidatingEventArgs.FormattedValue

There are many examples in the web, one can be found directly in the documentation of DataGridViewCellValidatingEventArgs in the MSDN. Take a look also to the documentation of the property DataGridViewCellValidatingEventArgs.FormattedValue

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

Note that the method IsValueValid(Object o) is not part of the DataGridView component, is just a naming example, you should declare it in your code and provide a body for the validation.

这篇关于如何在C#中取消CellEnter / CellLeave事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆