Vb.net DataGridView DateTimePicker列-添加长格式支持(日期和时间)

Vb.net DataGridView DateTimePicker列-添加长格式支持(日期和时间),vb.net,winforms,datagridview,datetimepicker,datetime-format,Vb.net,Winforms,Datagridview,Datetimepicker,Datetime Format,我正在尝试制作gridview Datetimepicker列,我成功了, 但我有一个小问题,当用户在gridview中编辑日期时 日期简写为“11/9/16”,但我想要的是日期和时间“11/9/16 2:34:45 AM” 这是我使用的代码: 日历列: Imports System Imports System.Windows.Forms Public Class CalendarColumn Inherits DataGridViewColumn Public Sub New()

我正在尝试制作gridview Datetimepicker列,我成功了, 但我有一个小问题,当用户在gridview中编辑日期时 日期简写为“11/9/16”,但我想要的是日期和时间“11/9/16 2:34:45 AM”

这是我使用的代码:

日历列:

Imports System
Imports System.Windows.Forms

Public Class CalendarColumn
Inherits DataGridViewColumn

Public Sub New()
    MyBase.New(New CalendarCell())
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 CalendarCell.
        If (value IsNot Nothing) AndAlso _
            Not value.GetType().IsAssignableFrom(GetType(CalendarCell)) _
            Then
            Throw New InvalidCastException("Must be a CalendarCell")
        End If
        MyBase.CellTemplate = value

    End Set
End Property

End Class
日历单元格:

Public Class CalendarCell
Inherits DataGridViewTextBoxCell

Public Sub New()
    ' Use the short date format.
    'Me.Style.Format = "d"
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 CalendarEditingControl = _
        CType(DataGridView.EditingControl, CalendarEditingControl)

    ' Use the default row value when Value property is null.
    If (Me.Value Is Nothing) Then
        ctl.Value = CType(Me.DefaultNewRowValue, DateTime)
    Else
        ctl.Value = CType(Me.Value, DateTime)
    End If
End Sub

Public Overrides ReadOnly Property EditType() As Type
    Get
        ' Return the type of the editing control that CalendarCell uses.
        Return GetType(CalendarEditingControl)
    End Get
End Property

Public Overrides ReadOnly Property ValueType() As Type
    Get
        ' Return the type of the value that CalendarCell 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 CalendarEditingControl
Inherits DateTimePicker
Implements IDataGridViewEditingControl

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

Public Sub New()
     Me.Format = DateTimePickerFormat.Long
    'Me.CustomFormat = "'Today is:' hh:mm:ss dddd MMMM dd, yyyy"
End Sub

Public Property EditingControlFormattedValue() As Object _
    Implements IDataGridViewEditingControl.EditingControlFormattedValue

    Get
        Return Me.Value.ToShortDateString()
    End Get

    Set(ByVal value As Object)
        Try
            ' This will throw an exception of the string is 
            ' null, empty, or not in the format of a date.
            Me.Value = DateTime.Parse(CStr(value))
        Catch
            ' In the case of an exception, just use the default
            ' value so we're not left with a null value.
            Me.Value = DateTime.Now
        End Try
    End Set

End Property

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

    Return Me.Value.ToShortDateString()

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
此代码用于添加列:

Dim col As New CalendarColumn() With {.HeaderText = "Date time"}
DataGridView1.Columns.Insert(5, col)


如何使时间变长。

若要以自定义格式显示日期和时间,应将格式指定给的属性。
DateTimePicker
CustomFormat
属性对于编辑格式很有用,但是对于在单元格中显示数据,您应该使用
column.DefaultCellStyle.format

例如,要显示日期和时间,如
2016/09/15 10:31:04 PM
,应使用
yyyy/MM/ddh:MM:ss tt
作为格式

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim dt = New DataTable()
    dt.Columns.Add("Date", GetType(DateTime))
    dt.Rows.Add(DateTime.Now)
    dt.Rows.Add(DateTime.Now)
    Dim column = New DataGridViewTextBoxColumn()
    column.DefaultCellStyle.Format = "yyyy/MM/dd h:mm:ss tt"
    column.DataPropertyName = "Date"
    Me.DataGridView1.Columns.Add(column)
    Me.DataGridView1.DataSource = dt
End Sub
有关自定义日期格式的详细信息,请参见:


DataGridView日期时间选择器列

下面是日期时间选择器列的完整源代码,其中包含一些修复。源代码已从中获取,我只是做了一些小更改和小修复。已进行更改以支持
时间
和长格式。此外,当单元格值为
DBNull.value
时,还进行了修复以防止异常:

Imports System
Imports System.Windows.Forms

Public Class CalendarColumn
    Inherits DataGridViewColumn

    Public Sub New()
        MyBase.New(New CalendarCell())
    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 CalendarCell.
            If (value IsNot Nothing) AndAlso _
                Not value.GetType().IsAssignableFrom(GetType(CalendarCell)) _
                Then
                Throw New InvalidCastException("Must be a CalendarCell")
            End If
            MyBase.CellTemplate = value

        End Set
    End Property

End Class

Public Class CalendarCell
    Inherits DataGridViewTextBoxCell

    Public Sub New()
        ' Use the short date format.
        Me.Style.Format = "yyyy/MM/dd h:mm:ss tt"
    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 CalendarEditingControl = _
            CType(DataGridView.EditingControl, CalendarEditingControl)

        ' Use the default row value when Value property is null.
        If (Me.Value Is Nothing OrElse IsDBNull(Me.Value)) Then
            ctl.Value = CType(Me.DefaultNewRowValue, DateTime)
        Else
            ctl.Value = CType(Me.Value, DateTime)
        End If
    End Sub

    Public Overrides ReadOnly Property EditType() As Type
        Get
            ' Return the type of the editing control that CalendarCell uses.
            Return GetType(CalendarEditingControl)
        End Get
    End Property

    Public Overrides ReadOnly Property ValueType() As Type
        Get
            ' Return the type of the value that CalendarCell 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 CalendarEditingControl
    Inherits DateTimePicker
    Implements IDataGridViewEditingControl

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

    Public Sub New()
        Me.Format = DateTimePickerFormat.Custom
        Me.CustomFormat = "yyyy/MM/dd h:mm:ss tt"
    End Sub

    Public Property EditingControlFormattedValue() As Object _
        Implements IDataGridViewEditingControl.EditingControlFormattedValue

        Get
            Return Me.Value.ToString("yyyy/MM/dd h:mm:ss tt")
        End Get

        Set(ByVal value As Object)
            Try
                ' This will throw an exception of the string is 
                ' null, empty, or not in the format of a date.
                Me.Value = DateTime.Parse(CStr(value))
            Catch
                ' In the case of an exception, just use the default
                ' value so we're not left with a null value.
                Me.Value = DateTime.Now
            End Try
        End Set

    End Property

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

        Return Me.Value.ToString("yyyy/MM/dd h:mm:ss tt")

    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

        ' Let the DateTimePicker handle the keys listed.
        Select Case key And Keys.KeyCode
            Case Keys.Left, Keys.Up, Keys.Down, Keys.Right, _
                Keys.Home, Keys.End, Keys.PageDown, Keys.PageUp

                Return True

            Case Else
                Return Not dataGridViewWantsInputKey
        End Select

    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
下面是测试代码:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim dt = New DataTable()
    dt.Columns.Add("Date", GetType(DateTime))
    dt.Rows.Add(DateTime.Now)
    dt.Rows.Add(DateTime.Now)
    Dim column = New CalendarColumn()
    column.DataPropertyName = "Date"
    Me.DataGridView1.Columns.Add(column)
    Me.DataGridView1.DataSource = dt
End Sub

@RezaAghaei我在哪里可以编辑我的代码,我已经尝试过了,但是没有任何改变,datetimepicker本身有什么改变,不是值,所以你能给我看一下吗?@RezaAghaei这是所有的代码,这是msn站点的代码,你可以在帖子的链接中查看源代码。感谢you@RezaAghaei有一个小问题,当我编辑日期时,显示的时间是12:00:00 AM,当我编辑日期时,如何显示当前时间您正在使用
DateTimePicker
进行编辑?您是否在日期时间选择器中显示了时间部分?有一个小问题,当我编辑日期时,显示的时间是12:00:00 AM,如何在编辑日期时显示当前时间。