开发者

UserControl in Custom DataGridViewCell Ignoring First Keystroke

开发者 https://www.devze.com 2023-01-05 06:36 出处:网络
开发者_运维问答I have a custom DataGridViewCell with a user-control as its editing control. The cell was built in the style of this article: http://msdn.microsoft.com/en-us/library/system.windows.form

开发者_运维问答I have a custom DataGridViewCell with a user-control as its editing control. The cell was built in the style of this article: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.initializeeditingcontrol.aspx

For the most part, this works great. The problem is that the regular behavior of a DataGridViewCell is to pass the keystroke used to enter EditMode to the control, but that's not happening for this cell.

Example:

I select the custom date cell, and type in "12/24/2008", the "1" begins EditMode, and "2/24/2008" appears in the cell.

How do I get the first keystroke to the editing control?

Public Class DataGridViewDateCell
    Public Overrides Function KeyEntersEditMode(ByVal e As System.Windows.Forms.KeyEventArgs) As Boolean
        'Any key-sequences with modifiers will not enter edit mode'
        If e.Control Or e.Shift Or e.Alt Then Return False

        'Accept numbers, '/', and '-''
        If (e.KeyCode >= Keys.NumPad0 And e.KeyCode <= Keys.NumPad9) OrElse _
            (Char.IsDigit(ChrW(e.KeyCode))) OrElse _
            e.KeyCode = Keys.Subtract OrElse _
            e.KeyCode = Keys.Divide OrElse _
            e.KeyCode = Keys.OemMinus OrElse _
            e.KeyCode = Keys.OemQuestion Then
            Return True
        End If

        'Any other keys should be ignored'
        Return False
    End Function

    Public Overrides ReadOnly Property EditType() As System.Type
        Get
            Return GetType(DataGridViewDateEditingControl)
        End Get
    End Property
End Class


I figured it out!

The custom control has a TextBox on it that always has focus (at least, within the usercontrol). When the user types, the keystrokes are going directly to the TextBox. But when the DataGridViewCell passes the keystroke to the control, it goes to the user control, not the TextBox.

I added this code to the usercontrol to fix it:

Private Sub ucDateTime_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
    DateText.AppendText(e.KeyChar)
    DateText_KeyPress(sender, e)
End Sub


Trap the keystroke in the form:

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If MyGrid.Focused AndAlso MyGrid.CurrentRow IsNot Nothing Then
        MyGrid.CurrentCell = MyGrid(4, MyGrid.CurrentRow.Index)
        MyGrid.BeginEdit(True)
    End If
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.KeyPreview = True
End Sub
0

精彩评论

暂无评论...
验证码 换一张
取 消