DataGridView如何通过按escape来检测用户何时退出编辑控件



在DataGridView中,我有CellValueChanged事件,当用户修改任何单元格值时,该事件被触发。当用户修改一个单元格时,值1被更改为2,然后用户单击下一个单元格并按Escape,第一个单元格中的值从2更改为1,cellvaluechange事件不会触发。我把值保存在对象的临时列表中,我也在这些列表中更新值。当用户按escape键并从编辑控制模式退出时触发哪个事件?

谢谢

响应cellenddit事件

还有这个地方:

    // Implements the IDataGridViewEditingControl.GetEditingControlFormattedValue method.
    public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
    {            
        if (context.ToString() == "Parsing, Commit")
        {
            // Do something here
        }
        return EditingControlFormattedValue;
    }

如果您在按下Escape键时在CellEndEdit事件中设置了断点,则其中一个调用将调用ProcessDataGridViewKey(...)方法。

public class DataGridView2 : DataGridView {
    private bool escapeKeyPressed = false;
    protected override bool ProcessDataGridViewKey(KeyEventArgs e) {
        escapeKeyPressed = (e.KeyData == Keys.Escape);
        return base.ProcessDataGridViewKey(e);
    }
    protected override void OnCellEndEdit(DataGridViewCellEventArgs e) {
        base.OnCellEndEdit(e);
        if (!escapeKeyPressed) {
            // process new value
        }
        escapeKeyPressed = false;
    }
}

注意:最初我尝试使用IsCurrentRowDirty属性,但它不一致。有时它显示false,但实际上单元格值是使用Enter键提交的。

dgv.CellEndEdit += (o, e) => {
    if (!dgv.IsCurrentRowDirty) { // not reliable
    }
};

最新更新