VB.NET Tips / Tricks / Examples and Help

VB.NET DateTimePicker blanks out when keying in a value

 I ran into an odd "bug" today in some production software. There was a datetimepicker control that had its "format" propery set to Custom, and its CustomFormat property set to MM/yyyy.

The purpose of the datetimepicker was to enter the expiration date for a credit card processing screen, so the user is only to enter the month and year values (no day required).

The problem was that they were entering the value of "11" for the month, and this caused the entire value being displayed in the datetimepicker to vanish.

As it turns out, the issue is related to the number of days in a month. This issue happened because today is 3/31/2011 (The datetimepicker defaults to todays date and it was displaying as 03/2011). They were entering November as the expiration month (11) and this was making the datetimepicker try to parse 11/31/2011 (even though the day is not displayed, it is still in the underlying date value of the control). Since November only has 30 days, this makes the datetimepicker blank out its value. Note that the underlying .value property will still reflect the previous valid value before it blanked out the display value. The bug took a little while to surface, since it could only occur on a day of a month where the day value is higher than the number of days in the month you are trying to enter.

The solution is that if you only need to collect a month and year, you should default the initial value to be the first day of the month (technically anything below 29 would work).

DateTimePicker1.Value =

New Date(Now.Year, Now.Month, 1)


Posted Mar 31 2011, 05:30 PM by Matthew Kleinwaks


© 2014 - ZerosAndTheOne.com - Hosting by Orcsweb (http://www.orcsweb.com/)
Powered by Community Server (Non-Commercial Edition), by Telligent Systems