C# – DataGridView navigation on Enter/Return

cdatagriddatagridviewnavigationwinforms

I'm trying to use the Enter key to move to the next (non-read-only) column in a DataGridView. Under normal circumstances, I handle the KeyDown event and everything works great.

However, when I'm editing a field, the Enter key always completes the edit and then moves to the next row.

Weirdly enough, I'm getting the following sequence of events in my test bed. (Numbers in parentheses are (rowIndex, columnIndex) of the event arg).

With no alternate navigation:

Press Enter (without editing the field):

PreviewKeyDown key = Return
KeyDown key = Return
CellLeave (0, 0)
RowLeave (0, 0)
CellValidating (0, 0)
CellValidated (0, 0)
RowEnter (1, 0)
CurrentCellChanged
CellEnter (1, 0)
SelectionChanged
KeyUp key = Return

Press Enter (while editing the field):

CellClick (0, 0)
CellBeginEdit (0, 0)
EditingControlShowing
    (I press Enter now)
CellLeave (0, 0)
RowLeave (0, 0)
CellValidating (0, 0)
CellValidated (0, 0)
CellEndEdit (0, 0)
RowEnter (1, 0)
CurrentCellChanged
CellEnter (1, 0)
SelectionChanged
KeyUp key = Return

i.e. I never get a PreviewKeyDown or KeyDown event when I press Enter while editing a field.

I tried hacking some alternate navigation in the event handlers. For test purposes, I always edit (r0, c0), and "navigate" by setting the CurrentCell property explicity to (r0, c1).

When I set the CurrentCell in CellEndEdit, I end up at (r1, c1). When I set the CurrentCell in KeyUp, I end up at (r0, c1), which is good, but only after it visibly selects (r1, c0). I suppose I could disable updates on the control during navigation, but this solution seems inelegant.

Any advice? Am I missing something?

Best Answer

After random flailing about careful analysis, it looks like the key is to derive from DataGridView and override DataGridView.ProcessDialogKey () and ProcessDataGridViewKey ()

Related Topic