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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| 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.