Search code examples
winformsdatetimepicker

Avoiding un-representable DateTime when using DateTimePicker CustomFormat MMM-yyyy


Suppose I have a DateTimePicker with a CustomFormat of MMM-yyyy which has been initialised to a value of 31st Oct 2013, this will display as Oct-2013.

If the select the Oct section of the control and press either up or down arrow, this generates an ArgumentOutOfRangeException - Year, Month, and Day parameters describe an un-representable DateTime.

Presumably it is changing the month without changing the day and there are only 30 days in September and November. Note, if the CustomFormat is dd-MMM-yyyy then no error is thrown because the day is automatically changed to the 30th.

How can I avoid or catch this error?

I can add code to ensure that the DateTimePicker is always initialised to the first of a month, but I want to allow the user to select the month and date from the calender dropdown, so I need to cope with the situation where the user has manually selected the 31st and then tries to change the month using the keyboard.


Solution

  • Just initialize it to Oct 1st. No exception, still the same display.

    And of course you'll need to adjust the value picked by the user to keep it on the 1st:

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e) {
            var dtp = (DateTimePicker)sender;
            dtp.Value = new DateTime(dtp.Value.Year, dtp.Value.Month, 1);
        }