Introduction
If you want to allow a user to select just a Month and Year, you can use the built-in DateTimePicker
by setting a few properties.
DateTimePicker1.ShowUpDown = True
DateTimePicker1.CustomFormat = "MMMMyyyy"
DateTimePicker1.Format = DateTimePickerFormat.Custom
This works most of the time except when the date displayed had a day that does not exist in the month you are trying to switch to. For example, DateTimePicker.value
is 10/31/2014
and you want to select September
. When the user hits the Down Arrow, you will get an exception:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Year, Month, and Day parameters describe an un-representable DateTime.
The solution is to make sure that the day of the month is always 1
.
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) _
Handles DateTimePicker1.ValueChanged
If DateTimePicker1.Value.Day <> 1 Then
DateTimePicker1.Value = DateSerial(DateTimePicker1.Value.Year, DateTimePicker1.Value.Month, 1)
End If
End Sub