DataGridView Events

本文关键字:Events DataGridView | 更新日期: 2023-09-27 18:19:50

每当用户在DataGridView控件的TextBox列中正常结束编辑模式时(无论用户是否实际修改了值;但不是当用户通过按ESC取消编辑模式时),我都需要执行任务。

我尝试了DataGridView控件本身和编辑控件的几个事件,但都没有达到我想要的效果:

DataGridView.CellValidatingDataGridView.CellValidated:

每当用户选择另一个单元格时,即使该单元格未处于编辑模式,也会触发这些事件。我尝试在CellValidating事件中检查IsCurrentCellDirty属性。这几乎是我所需要的,但只有当用户实际更改值时才设置IsCurrentCellDirty。但是,当用户通常在没有更改任何内容的情况下结束编辑模式时,我也需要执行该任务。当用户取消编辑模式时,不会触发这些事件,这很好。

DataGridView.CellValueChanged

此事件也经常触发(当以编程方式设置单元格的值时也会触发)。

DataGridView.CellEndEdit

这次活动几乎是我想要的。但当用户按ESC键取消编辑模式时,它也会被触发。有没有办法检查CellEndEdit事件中是否取消了编辑模式?

DataGridView.CellParsing

这次活动几乎是我想要的。但是,当用户在没有更改任何内容的情况下结束编辑模式时,它不会被触发。

编辑控件的ValidatingValidated事件

我在DataGridView.EditingControlShowing事件中注册了这些事件。它们几乎可以做我想要的事情,但当用户按ESC取消编辑模式时,它们也会被解雇。有没有办法检查这些事件中的编辑模式是否被取消?

对于我可以注册的事件和/或我可以检查以实现所需行为的标志,有任何其他建议吗

DataGridView Events

您可以在DataGridViewEditingControlShowing事件中注册到EditingControlPreviewKeyDown事件。从那里可以检测编辑控件中是否按下了escape,并设置将由CellEndEdit事件读取的标志。

您可以从方法名称推断出要注册的必要事件。这假设您的类中有一个名为escapePressed的bool字段,它(毫不奇怪)是按下escape的标志。

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    e.Control.PreviewKeyDown -= Control_PreviewKeyDown; //avoid attaching multiple handlers in case control is cached
    e.Control.PreviewKeyDown += new PreviewKeyDownEventHandler(Control_PreviewKeyDown);
}
void Control_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        Console.WriteLine("escape pressed");
        escapePressed = true;
    }
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (!escapePressed)
    {
        Console.WriteLine("do your stuff"); //escape was not pressed.
    }
    else escapePressed = false; //reset the flag
}

以下是我的解决方法:

引入

private DataGridViewCell cellBeingEdited = null;

DataGridView.EditingControlShowing

cellBeingEdited = DataGridView.CurrentCell;

DataGridView.CellEndEdit

cellBeingEdited = null;

然后我可以使用DataGridView.CellValidating事件,该事件在取消编辑时不会触发,并检查我的cellBeingEdited字段:

if (DataGridView.CurrentCell != cellBeingEdited) return;