C# – make DataGridView.EndEdit trigger the CellValidating event


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.

Best Solution

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;
            CurrentCell = null;
            CurrentCell = currentCell;
            return true;
        return base.ProcessDialogKey(keyData);