Oct
20/10
How to Add DateTimePicker/Calendar Control in DataGridView
Last Updated on Wednesday, 20 October 2010 04:00
Written by Kyle
Wednesday, 20 October 2010 03:56

How to Add DateTimePicker/Calendar Control in DataGridView

Vb.Net

Create the following 3 classes :

  1. CalendarColumn

  2. 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
  3. CalendarCell

  4. 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
  5. CalendarEditingControl

  6. Public 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.Short
        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
     
        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

Add the following lines to Form Load

Dim ColumnName As New CalendarColumn()
Me.DataGridViewName.Columns.Add(ColumnName)

View more with C++, C#, F#, JScript : http://msdn.microsoft.com/en-us/library/7tas5c80.aspx


9 Comments
  1. Commentsrockie667   |  Monday, 18 July 2011 at 9:24 pm

    Hello,
    I use the C# Version of this Control and have to problems with it. First is: if a calendarCell is selected and I want to edit it by keyboard, then for me it is not to predict where the focus will be (is it day or month or year. So: how can I ensure that after first hitting a number, the day will be edited. Second, I would like the following behaviour of the controll: After two keystrokes for day-field, the focus should automatically change to month value editing.

    So you have any ideas of realising this? Thank you so much in advance!

    rockie

  2. CommentsAdobe For Mac   |  Friday, 30 December 2011 at 12:06 pm

    Adobe For Mac…

    [...]How to Add DateTimePicker/Calendar Control in DataGridView | Kyle's Blog[...]…

  3. Commentsscript nulled   |  Thursday, 05 January 2012 at 7:42 am

    script nulled…

    [...]How to Add DateTimePicker/Calendar Control in DataGridView | Kyle's Blog[...]…

  4. Commentsultimate demon discount   |  Monday, 09 January 2012 at 11:23 am

    ultimate demon discount…

    [...]How to Add DateTimePicker/Calendar Control in DataGridView | Kyle's Blog[...]…

  5. CommentsFAHD   |  Saturday, 25 February 2012 at 4:31 pm

    THANKS TO HELP

  6. CommentsAnil   |  Wednesday, 07 March 2012 at 12:48 pm

    Thank You So Much………………..

  7. Comments%anchor_text%   |  Tuesday, 14 May 2013 at 11:46 pm

    I have learn a few excellent stuff here. Definitely value bookmarking for revisiting.

    I surprise how a lot effort you place to create
    such a magnificent informative web site.
    %anchor_text% recently posted..%anchor_text%

  8. Commentscars   |  Friday, 31 May 2013 at 7:54 am

    All large purchases are always intimidating, especially if you are uninformed about the industry.

    One of the scariest purchases is buying cars. Many people
    fear they are getting ripped off and you surely don’t want that. Avoid buying a lemon by looking through these great tips and tricks regarding car purchases.
    cars recently posted..cars

  9. Commentswebsite design templates   |  Friday, 13 December 2013 at 2:58 pm

    Hello There. I found your blog the use of msn. That is a really smartly written article.
    I will be sure to bookmark it and come back to read extra of your
    useful info. Thanks for the post. I will definitely return.
    website design templates recently posted..website design templates


Leave a Reply






*

CommentLuv badge


Content Protected Using Blog Protector By: PcDrome.