How to prevent Enter key from ending EditMode in DataGridView?

I have a custom DataGridView control in a Windows-Forms application. When the user presses the Enter key, I do not want something to happen. I have already overridden the OnKeyPress method in my custom DataGridView to prevent the SelectedCell property from changing. This works well when a cell is selected but not edited. However, if the cell is in edit mode when you press Enter, the CellEndEdit event still fires, and the SelectedCell property subsequently changes.

How can I stop the Enter key from ending edit mode in a DataGridView control?

+2
winforms datagridview
source share
1 answer

I found the answer thanks to varocarbas , which commented below on my original question. My assumption is that the CellEndEdit event is fired somewhere after the ProcessCmdKeys () method is called, but before the OnKeyPress () call because the priority of the ENTER key is higher than usual (this is the command key). This explains why I could not change the behavior while the cell is still in EditMode using OnKeyPress ().

The created custom DataGridView, which prevents any action after pressing the ENTER key in the 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 

Someone please correct me if my assumption of a call sequence is inadequate. Also note that this override of ProcessCmdKey () made my previously mentioned override of the OnKeyPress () method unnecessary.

+3
source share

All Articles