views:

144

answers:

1

Hi,

I want to validate and commit the value entered in the DataGridViewCell ONLY when the user presses the 'Enter' key.

If the users presses any other key or mouse button (Arrow keys, Pressing a different cell using the mouse...), I want the behavior to be similar to the 'ESC' key: Move the focus to the new cell and revert the edited cell value to its previous value.

+1  A: 

The following might work.

Handle the CellValidating and cancel any changes unless the last key pressed was enter.

EDIT:

Subclass the DataGridView control with your own class and add the following code to it:

  private bool m_lastWasEnter = false;
  public bool LastWasEnter()
  {
     return m_lastWasEnter;
  }
  protected override bool ProcessDialogKey(System.Windows.Forms.Keys keyData)
  {
     m_lastWasEnter = keyData == Keys.Return;
     return base.ProcessDialogKey(keyData);
  }

Then you could just add the following to the handler of the CellValidating event:

e.Cancel = !instanceOfYourControl.LastWasEnter();

This won't give you exactly what you want but should make sure that it'll only stop the editing if the user pressed enter at least and you should be able to modify it to get your exact requirements to be met.

ho1
KeyDown is never called when I'm in edit mode. Any suggestions?
Eldad
Please see amended answer which might work.
ho1
The KeyPress doesn't capture the 'Enter" key.
Eldad
Please see amended answer which will work (this one I had time to test).
ho1
At last... It works perfectly. Thank you!!!
Eldad