3
votes

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.

2

2 Answers

6
votes

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);
    }
0
votes

Yeah I know that answer is already posted and accepted by OP. but, when i have tried this solution it was not working form me.

Ok, let's take an example: If I set the date format for DateTimePicker to MM/yyyy and I am trying to select month from 09 to 10 (September to October) by pressing Down arrow key Then, it will throw the exception and will bring me at the Program.cs file.

The solution is same as given by Hans Passant but, the only difference is that just we need to use PreviewKeyDown event instead of ValueChanged. I don't know whether KeyDown event also works for this. But, I have tested it with PreviewKeyDown event and it was working fine.