VB.NET TimePicker 的 DataGridView 单元格更新问题:Enter 键不更新显示的值

VB.NET Update Issue in DataGridView Cell for TimePicker: Enter Key Does not Update Displayed Value

我有一个奇怪的问题,即在 VB.NET 中重载 DataGridView 的单元格以使用 DateTimePicker(允许用户 select 日期和时间)。我将 Microsoft implementation of a Calendar picker 修改为日历和时间选择器。当我输入新日期并按 ENTER 键时,DataGridView 单元格中显示的日期是旧日期。

只有在该键上再次按 ENTER,或单击该单元格并单击离开时,才会显示新值。

如果我单击该单元格,输入新日期,然后单击另一个单元格,该单元格会显示正确的日期时间值。然后,显示的日期与我输入的相符。它正在使用我遇到问题的 ENTER 键。

我修改了微软重载代码如下:

Public Class TimeColumn
    Inherits DataGridViewColumn

    Public Sub New()
        MyBase.New(New TimeCell())
    End Sub

    Public Overrides Property CellTemplate() As DataGridViewCell
        Get
            Return MyBase.CellTemplate
        End Get
        Set(ByVal value As DataGridViewCell)
            ' Ensure that the cell used for the template is a TimeCell.
            If (value IsNot Nothing) AndAlso _
                Not value.GetType().IsAssignableFrom(GetType(TimeCell)) _
                Then
                Throw New InvalidCastException("Must be a TimeCell")
            End If
            MyBase.CellTemplate = value
        End Set
    End Property

End Class

Public Class TimeCell
    Inherits DataGridViewTextBoxCell

    Public Sub New()
        ' Use the short date format.            
        Me.Style.Format = "MM/dd/yy  h:mm tt"
        'm_isTime = True
    End Sub
    Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, _
        ByVal initialFormattedValue As Object, _
        ByVal dataGridViewCellStyle As DataGridViewCellStyle)

        ' Set the value of the editing control to the current cell value.
        MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, _
            dataGridViewCellStyle)

        Dim ctl As New TimeEditingControl
        ctl = CType(DataGridView.EditingControl, TimeEditingControl)
        ctl.CustomFormat = "MM/dd/yyyy h:mm tt"
        Me.Value = ctl.Value

    End Sub

    Public Overrides ReadOnly Property EditType() As Type
        Get
            ' Return the type of the editing contol that TimeCell uses.
            Return GetType(TimeEditingControl)
        End Get
    End Property

    Public Overrides ReadOnly Property ValueType() As Type
        Get
            ' Return the type of the value that TimeCell contains.            
            Return GetType(DateTime)
        End Get
    End Property

    Public Overrides ReadOnly Property DefaultNewRowValue() As Object
        Get
            ' Use the current date and time as the default value.
            Return DateTime.Now
        End Get
    End Property

End Class

Class TimeEditingControl
    Inherits DateTimePicker
    Implements IDataGridViewEditingControl

    Private dataGridViewControl As DataGridView
    Private valueIsChanged As Boolean = False
    Private rowIndexNum As Integer

    Public Sub New()
        Me.Format = DateTimePickerFormat.Custom
    End Sub
    Public Property EditingControlFormattedValue() As Object _
        Implements IDataGridViewEditingControl.EditingControlFormattedValue

        Get
            Return Me.Value.ToShortDateString()
        End Get

        Set(ByVal value As Object)
            If TypeOf value Is String Then
                Me.Value = DateTime.Parse(CStr(value))
            End If
        End Set

    End Property

    Public Function GetEditingControlFormattedValue(ByVal context _
        As DataGridViewDataErrorContexts) As Object _
        Implements IDataGridViewEditingControl.GetEditingControlFormattedValue

        Dim result, tempDateTime As DateTime
        tempDateTime = Me.Value      

        Return tempDateTime.ToString            
    End Function


    Public Sub ApplyCellStyleToEditingControl(ByVal dataGridViewCellStyle As  _
        DataGridViewCellStyle) _
        Implements IDataGridViewEditingControl.ApplyCellStyleToEditingControl

        Me.Font = dataGridViewCellStyle.Font
        Me.CalendarForeColor = dataGridViewCellStyle.ForeColor
        Me.CalendarMonthBackground = dataGridViewCellStyle.BackColor

    End Sub

    Public Property EditingControlRowIndex() As Integer _
        Implements IDataGridViewEditingControl.EditingControlRowIndex

        Get
            Return rowIndexNum
        End Get
        Set(ByVal value As Integer)
            rowIndexNum = value
        End Set

    End Property



    Public Function EditingControlWantsInputKey(ByVal key As Keys, _
        ByVal dataGridViewWantsInputKey As Boolean) As Boolean _
        Implements IDataGridViewEditingControl.EditingControlWantsInputKey
        Dim lDateTime As DateTime
        ' Let the DateTimePicker handle the keys listed.
        Select key And Keys.KeyCode

            Case Keys.Enter

                Console.WriteLine(DateTime.Now.ToString & "." & DateTime.Now.Millisecond.ToString & ": EditingControlWantsInputKey--Detected [ENTER] key.")
        End Select
        valueIsChanged = True
        Console.WriteLine("EditingControlWantsInputKey (" & Me.Value & ")")
        Dim lDataGridView1 As DataGridView
        lDataGridView1 = Me.dataGridViewControl
        lDataGridView1.BeginEdit(True)
        lDataGridView1.BeginEdit(False)
        Return True


    End Function

    Public Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) _
        Implements IDataGridViewEditingControl.PrepareEditingControlForEdit

        ' No preparation needs to be done.

    End Sub

    Public ReadOnly Property RepositionEditingControlOnValueChange() _
        As Boolean Implements _
        IDataGridViewEditingControl.RepositionEditingControlOnValueChange

        Get
            Return False
        End Get

    End Property

    Public Property EditingControlDataGridView() As DataGridView _
        Implements IDataGridViewEditingControl.EditingControlDataGridView

        Get
            Return dataGridViewControl

        End Get
        Set(ByVal value As DataGridView)
            dataGridViewControl = value
        End Set

    End Property

    Public Property EditingControlValueChanged() As Boolean _
        Implements IDataGridViewEditingControl.EditingControlValueChanged

        Get
            Return valueIsChanged
        End Get
        Set(ByVal value As Boolean)
            valueIsChanged = value
        End Set

    End Property

    Public ReadOnly Property EditingControlCursor() As Cursor _
        Implements IDataGridViewEditingControl.EditingPanelCursor

        Get
            Return MyBase.Cursor
        End Get

    End Property

    Protected Overrides Sub OnValueChanged(ByVal eventargs As EventArgs)

        ' Notify the DataGridView that the contents of the cell have changed.
        valueIsChanged = True
        Me.EditingControlDataGridView.NotifyCurrentCellDirty(True)
        MyBase.OnValueChanged(eventargs)

    End Sub

End Class

到目前为止我的发现:

  1. 奇怪的是 Public 属性 EditingControlValueChanged() As Boolean Implements IDataGridViewEditingControl.EditingControlValueChanged 没有检测到 ENTER关键!您可以看到我为该事件输入了一些调试代码,以查看它是否检测到按下 ENTER 键。

  2. 事件 Public 属性 EditingControlValueChanged() As Boolean Implements IDataGridViewEditingControl.EditingControlValueChanged 没有检测到值变化( boolean valueIsChanged 设置为 false)直到第二次按下 ENTER 键,此时它设置为 true。

  3. 我还尝试更新 DataGridView 的 CellEndEdit 事件中的单元格值,但这没有用。

  4. 我已经更新了我的 Visual Studio Express 2013,以防它是一个 Micosoft 错误。

知道如何让显示的值与按下 ENTER 键时输入的值相匹配吗?谢谢

我最初的评论肯定是错误的。重现您的问题后,我注意到一些事情 funny/frustrating:在下一行的 EditingControlWantsInputKey 方法中放置一个断点,允许更新按预期发生(调试 fix的问题):

Select key And Keys.KeyCode

这太烦人了,在我沮丧的情况下,我疯狂地连续测试了月份条目:1、2、3、...、12

那时我注意到:第 10-12 个月更新正确。事实上,输入 01 已正确更新。我随后的研究使我找到了 comments section of this article, where user Dean Wiles in his comment titled Changes lost using Tab or Enter provides this Microsoft support source,它表明:

The ValueChanged event of the [DateTimePicker] is raised only after you type any one of the following:

  • All the digits of a year.
  • All the digits of a day.
  • All the digits of a month.

这可以通过将他的代码的以下 vb.net 版本添加到您的 TimeEditingControl class:

来解决
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
    Select Case keyData And Keys.KeyCode
        Case Keys.Enter, Keys.Tab
            Me.dataGridViewControl.Focus()
            Exit Select
    End Select

    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

C# 转换

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{

    switch (keyData & Keys.KeyCode)
    {
        case Keys.Enter:
        case Keys.Tab:
            this.dataGridView.Focus();
            break; 
    }

    return base.ProcessCmdKey(ref msg, keyData);

}