DataGridView how to detect when user comesout from editing control by pressing escape?
Asked Answered
F

3

6

In DataGridView I have CellValueChanged event, when user modify any cell value, this event is fired. When user modify one cell, value 1 is changed to 2, then user click the next cell and press Escape, value in first cell is changed from 2 to 1, CellValueChanged event isn't fired. I keep values in temporary lists of object, and I have update values in these lists too. Which event is fired when user press escape and comes out from editing control mode ?

Thanks

Fruiterer answered 25/12, 2011 at 18:51 Comment(0)
D
2

React to the CellEndEdit event.

Duval answered 25/12, 2011 at 18:55 Comment(3)
How do you know Escape was pressed?Eolic
How about if the users clicks on Cell 2, changes something. then decides whoops, I better not do that. so they hit escape? that fires the validating event first.Autolithography
This is clearly an incorrect answer! The CellEndEdit event occurs in both cases: when edit operation is cancelled and completed. It's by no mean a way to detect ESC exit from editing control. It's wrong it's accepted as an answer since is misleading. It could be a partial answer since we can check (with the help of CellBeginEdit event) if the cell value changed. If not, then... it could be ESC action, or the user hasn't changed anything, but pressed Enter instead. If you don't have to assign separate action to Enter without changes, it's enough. If you need strict distinction - it's not.Sinistrad
C
1

There is also this place:

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

        return EditingControlFormattedValue;
    }
Chickenhearted answered 27/4, 2014 at 21:56 Comment(0)
G
1

If you set a break-point in the CellEndEdit event when the Escape key is pressed, one of the calls made is to the ProcessDataGridViewKey(...) method.

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

Note: Originally I tried using the the IsCurrentRowDirty property, but it's not consistent. Sometimes it says false, but actually the cell value was committed using the Enter key.

dgv.CellEndEdit += (o, e) => {
    if (!dgv.IsCurrentRowDirty) { // not reliable
    }
};
Gherkin answered 3/5, 2022 at 20:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.