Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A Month/Year Date Picker in VB.NET

0.00/5 (No votes)
3 Nov 2014 1  
A month/year date picker in VB.NET

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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here