如何防止Enter键结束DataGridView中的EditMode? [英] How to prevent an Enter key press from ending EditMode in a DataGridView?

查看:70
本文介绍了如何防止Enter键结束DataGridView中的EditMode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows Forms应用程序中有一个自定义DataGridView控件。当用户按下Enter键时,我什么都不想发生。我已经重写了自定义DataGridView中的OnKeyPress方法,以防止SelectedCell属性发生更改。当选定一个单元格但未对其进行编辑时,此方法正常工作。但是,如果在按下Enter键时单元格处于编辑模式,则仍会触发CellEndEdit事件,并且随后更改了SelectedCell属性。

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.

如何停止Enter键结束DataGridView控件上的编辑模式?

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

推荐答案

我已经找到了答案,这要感谢 varocarbas ,他在我的原始问题下方进行了评论。我的假设是,由于ENTER键的优先级高于普通键(它是Command键),因此在ProcessCmdKeys()方法调用之后但在OnKeyPress()调用之前的某个位置触发了CellEndEdit事件。这解释了为什么当单元格仍处于使用OnKeyPress()的EditMode时无法更改行为的原因。

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().

我创建的自定义DataGridView可以防止任何操作在DataGridView中按Enter键后发生,可以在下面看到:

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

如果我对呼叫顺序的假设不足,请纠正我。还要注意,此ProcessCmdKey()重写使我前面提到的OnKeyPress()方法的重写成为不必要。

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.

这篇关于如何防止Enter键结束DataGridView中的EditMode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆