How can I make a choice of time for choosing a date, always contain the last day of the month, showing only the month and year?

I have a DateTimePicker that I set to display only month and year as follows:

myDateTimePicker.Format = DateTimePickerFormat.Custom; myDateTimePicker.CustomFormat = "MMMM yyyy"; myDateTimePicker.ShowUpDown = true; 

However, I want the date value to always be the last day of the selected month, so I set the DateTime in the ValueChanged event using:

 DateTime selectedDate = myDateTimePicker.Value; DateTime lastDayOfMonth = new DateTime( selectedDate.Year, selectedDate.Month, DateTime.DaysInMonth(selectedDate.Year, selectedDate.Month)); myDateTimePicker.Value = lastDayOfMonth; 

The problem is that if I have a month as the selected month and I change the month to February using the up / down controls, I get the following error before I can handle the ValueChanged event:

 ArgumentOutOfRangeException was unhandled Year, Month, and Day parameters describe an un-representable DateTime. 

This is understandable because the date was March 31, and it changes until February 31, which is an invalid date. However, I want to change it until February 28 (or February 29).

How can i achieve this?

+6
source share
2 answers

Very strange, I tried to reproduce your problem, and when I switch from March to February, my control just doesn’t display anything ... Maybe we have different versions of the frameworks that handle the same error in different ways.

In any case, one of the solutions would be to set the date and time collector on the first of each month, and when you need this value, you can simply use your code in the form in which it is now:

 DateTime lastDayOfMonth = new DateTime( selectedDate.Year, selectedDate.Month, DateTime.DaysInMonth(selectedDate.Year, selectedDate.Month)); 

Since you never use the daily value of your datitude assistant, you can simply set it to 1, which will always give the existing date.

This decision leaves me somehow bad, because you are using a date that is different from the date you get from your control - always a possible source of errors, IMO. Remember to add comments to your code explaining why you are doing this; -)

+4
source

I would probably use the 1st month, for example Treb Selected, but increase the DateTimePicker so that when you do this:

MyDateTimePicker.Value

he would do something like this:

 get{ return value.addMonths(1).addDays(-1) } 
+2
source

Source: https://habr.com/ru/post/910703/


All Articles