Tech Blog‎ > ‎

VB.NET - Nullable DateTimePicker

posted Feb 19, 2010, 1:39 PM by Victor Zakharov   [ updated Feb 19, 2010, 1:43 PM ]

One of the popular ways to do this - change format to " " (space) whenever null value is being set and roll it back to the old format on anything else. I have been looking for clean implementation of this approach. In the end I decided to write my own, using source code available on the net. Here is what I came up with: 

Public Class MyDateTimePicker : Inherits DateTimePicker

  Private oldFormat As DateTimePickerFormat
  Private oldCustomFormat As String
  Private _value As Object

  Public Sub New()
    _value = MyBase.Value
  End Sub

  Public Overloads Property Value()
    Get
      Return _value
    End Get
    Set(ByVal value)
      If value = DateTime.MinValue Then
        If _value IsNot Nothing Then
          oldFormat = Me.Format
          oldCustomFormat = Me.CustomFormat
        End If

        Me.Format = DateTimePickerFormat.Custom
        Me.CustomFormat = " "
        _value = Nothing
      Else
        If _value Is Nothing Then
          Me.Format = oldFormat
          Me.CustomFormat = oldCustomFormat
        End If

        MyBase.Value = value
        _value = value
      End If
    End Set
  End Property

  Private Sub MyDateTimePicker_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    Select Case e.KeyCode
      Case Keys.Delete
        Me.Value = DateTime.MinValue
    End Select
  End Sub

  Protected Overrides Sub OnValueChanged(ByVal eventargs As System.EventArgs)
    If _value Is Nothing Then
      Me.Format = oldFormat
      Me.CustomFormat = oldCustomFormat
    End If

    _value = MyBase.Value
  End Sub

End Class

In the code above, Delete key sets value to null. And it keeps Nothing until reassigned to something else. You can download test project from here.

ċ
NullableDateTimePicker.zip
(13k)
Victor Zakharov,
Feb 19, 2010, 1:42 PM
Comments