DataGridView DateTimePicker列-添加长格式支持(日期和时间) [英] DataGridView DateTimePicker Column - add Long Format support (Date and the Time)

查看:98
本文介绍了DataGridView DateTimePicker列-添加长格式支持(日期和时间)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使gridview Datetimepicker列成功,但是
却成功了,但是我有一个小问题,当用户在gridview
中编辑日期时,日期会以短的 11/9 / 16,但我要的是日期和时间在一起 11/9/16 2:34:45 AM

I'm trying to make gridview Datetimepicker column and i succeeded, but i have a little problem that when the user edit the date in the gridview the date appear in short "11/9/16" but what i want is the date and the time together"11/9/16 2:34:45 AM"

这是我使用的代码:

CalendarColumn:

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:

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:

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)

源代码

我要花多少时间呢?

推荐答案

要以自定义格式显示日期和时间,应将格式分配给 Format 属性。 microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.defaultcellstyle(v=vs.110).aspx rel = nofollow> DefaultCellStyle DateTimePicker CustomFormat 属性对于编辑格式很有用,但是对于在单元格中显示数据,您应该使用 column.DefaultCellStyle.Format

To show a date and time in custom format, you should assign format to Format property of DefaultCellStyle. The CustomFormat property of DateTimePicker is useful for editing format but for displaying data in cell you should use column.DefaultCellStyle.Format.

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

For example to show date and time like 2016/09/15 10:31:04 PM you should use yyyy/MM/dd h:mm:ss tt as format.

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

有关自定义日期的更多信息格式请参见:

For more information about custom date formats see:

  • Custom Date and Time Format Strings

DataGridView DateTimePicker列

日期时间选择器列的完整源代码,并进行了一些修复。来源取自 MSDN ,我做了一些小的更改和小的修复。进行了更改,以支持 Time 和长格式。还进行了修复,以防止在单元格值为 DBNull.Value 时发生异常:

Here is the full source code of date time picker column with some fixes. The source has been taken from MSDN and I just made some small changes and a small fix. The changes has been made to support Time and long format. Also the fix has been done to prevent exception when the cell value is 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

这篇关于DataGridView DateTimePicker列-添加长格式支持(日期和时间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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