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

时间:2016-09-15 17:35:13

标签: vb.net winforms datagridview datetimepicker datetime-format

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

这是我使用的代码:

CalendarColumn:

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

CalendarCell:

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

CalendarEditingControl:

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)

source Code

如何随着时间的推移做多久。

1 个答案:

答案 0 :(得分:2)

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

例如,要显示2016/09/15 10:31:04 PM之类的日期和时间,您应该使用yyyy/MM/dd h: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 DateTimePicker列

以下是日期时间选择器列的完整源代码,其中包含一些修复程序。来源取自MSDN,我只做了一些小修改和一个小修复。已进行更改以支持Time和长格式。此外,还修复了单元格值为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