Click here to Skip to main content
15,894,825 members
Articles / Programming Languages / Visual Basic
Tip/Trick

A Month/Year Date Picker in VB.NET

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
3 Nov 2014CPOL 27.9K   609   5  
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.

VB.NET
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.

VB.NET
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --