可以让DataGridView.EndEdit触发CellValidating事件吗? [英] Can I make DataGridView.EndEdit trigger the CellValidating event?

查看:468
本文介绍了可以让DataGridView.EndEdit触发CellValidating事件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WinForms应用程序中使用了DataGridView。我的主要目标是使Enter键不移动到网格中的下一行。我仍然希望输入密钥验证并结束编辑模式。



我发现这个FAQ条目和子类DataGridView来覆盖ProcessDialogKey()。如果按下的键是Enter,我调用EndEdit(),否则我调用base.ProcessDialogKey()。



除了CellValidating事件没有被触发,它的效果很好。



目前,我只是在调用EndEdit之前手动调用验证逻辑,但似乎我缺少一些东西。



我想我可以打电话给OnCellValidating,但是我会担心我会失去一些其他的事件。我真正想要的是EndEdit()的一些风格,就像在禁用添加的网格的最后一行按Enter键一样。

解决方案

在更改CurrentCell之前,CellValidating不会被调用。所以我这样做的方法是改变CurrentCell,然后切换回当前的。

  protected override bool ProcessDialogKey键keyData)
{
if(keyData == Keys.Enter)
{
DataGridViewCell currentCell = CurrentCell;
EndEdit();
CurrentCell = null;
CurrentCell = currentCell;
返回true;
}
return base.ProcessDialogKey(keyData);
}


I'm using a DataGridView in my WinForms application. My main objective is to make the Enter key not move to the next row in the grid. I still want the enter key to validate and end edit mode.

I found this FAQ entry and subclassed DataGridView to override ProcessDialogKey(). If the key pressed is Enter, I call EndEdit(), otherwise I call base.ProcessDialogKey().

It works great, except the CellValidating event isn't fired.

Currently, I'm just manually calling my validation logic before I call EndEdit, but it seems like I'm missing something.

I guess I could call OnCellValidating, but then I'd be worried I'm missing some other event. What I really want is some flavour of EndEdit() that behaves just like pressing enter on the last row of a grid with adding disabled.

解决方案

CellValidating doesn't get called until you change the CurrentCell. So the way I kludged around this was to change the CurrentCell, then switch back to the current one.

    protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.Enter)
        {
            DataGridViewCell currentCell = CurrentCell;
            EndEdit();
            CurrentCell = null;
            CurrentCell = currentCell;
            return true;
        }
        return base.ProcessDialogKey(keyData);
    }

这篇关于可以让DataGridView.EndEdit触发CellValidating事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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