2

I have a custom DataGridView control in a Windows-Forms application. When a user presses the Enter key, I do not want anything to happen. I have already overridden the OnKeyPress method in my custom DataGridView to prevent the SelectedCell property from changing. This works alright when a cell is selected but not being editted. However, if a cell is in Edit mode when Enter is pressed, the CellEndEdit event is still fired and the SelectedCell property is subsequently changed.

How can I stop the Enter key from ending Edit Mode on my DataGridView control?

D. Bunnell
  • 463
  • 6
  • 12
  • I am afraid that the only way you have to account for what happens during the edit mode is hooking the keys (as far a there is no event allowing you to have full control on this situation). Here you have a post (in C#) which links to what seems to be a solution for this problem: http://stackoverflow.com/questions/2527371/how-can-i-change-what-happens-when-enter-key-is-pressed-on-a-datagridview – varocarbas Oct 28 '13 at 10:34
  • thanks, using your link I found the answer I was looking for! – D. Bunnell Oct 28 '13 at 12:31
  • I am happy of having been of help. – varocarbas Oct 28 '13 at 12:42

1 Answers1

4

I have found the answer, thanks to varocarbas, who commented below my original question. My assumption is that the CellEndEdit Event is fired somewhere following the ProcessCmdKeys() method-call but before the OnKeyPress() call due to the precedence of the ENTER key being higher than a normal key (it's a Command key). This explains why I was unable to change the behavior while a cell was still in EditMode using OnKeyPress().

The custom DataGridView that I created, which prevents any action from occurring following an ENTER-key press in a DataGridView, can be seen below:

Public Class clsModifyDataGridView
   Inherits Windows.Forms.DataGridView

   ''' <summary>
   ''' Changes the behavior in response to a Command-precedence key press
   ''' </summary>
   ''' <returns>True if we handled the key-press, otherwise dependent on default behavior</returns>
   Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
      ' Was the ENTER key pressed?
      If keyData = Keys.Enter Then     ' YES
          ' DO NOTHING 
          Return True
       End If

       ' Handle all other keys as usual
       Return MyBase.ProcessCmdKey(msg, keyData)
   End Function
End Class

Somebody please correct me if my assumption about the call-sequence is inadequate. Also note, this ProcessCmdKey() override made my previously mentioned override of the OnKeyPress() method unnecessary.

Community
  • 1
  • 1
D. Bunnell
  • 463
  • 6
  • 12
  • 1
    ProcessCmdKey is called before anything else (http://msdn.microsoft.com/en-us/library/system.windows.forms.control.processcmdkey.aspx) – varocarbas Oct 28 '13 at 12:42