1
votes

When I switch Months in datetime picker using left and right Arrow by default it selects 1st day of every month.

I don't want this to be happen in my case. I want to have same date (the date that is selected before datetime picker is open) unless the User selects any other date.

1
So do you mean that if today you open the datetime picker and April 5 is selected, then you click the right arrow to change to May, you want May 5 to be selected?Jeff Anderson
How will that work when the user has selected January 31st and presses the right arrow key? Should it go to February 28th? I bet the picker designers set it to the 1st to avoid such a situation.Dan Wilson
screencast.com/t/XHF3Pq3U Refer to screencast. April 5th is my starting date before calendar is open. Later when I switched months the date got change to May1st and June 1st..... I want the date to be April 5th when switched between months. The date should change only if user clicks any other date.Movva
So you want a MonthPicker, not a DatePicker. That's a ComboBox or DomainUpDown.Hans Passant

1 Answers

2
votes

This is behavior by design.

In WinForms

The System.Windows.Forms.DateTimePicker relies on Win32 API components. That means much of the control rendition and interaction code is native code and cannot easily be changed from within .NET.

You can attempt something like this, subclassing DateTimePicker and overriding the WndProc handler, so you can write your own implementation of the WmDateTimeChange function (original here) and force the day of value to the same day as validTime as you detect a month jump. Such modifications are likely to break in future versions of Windows and therefore discouraged for anything other than learning and experimenting.

In WPF

The DatePicker uses a Calendar control to represent its popup. When we look in Reference Source what happens when the actions OnNextClick and OnPreviousClick are invoked from the months view, we can see that the DiscardDayTime function is called to switch to the first of the target month:

return new DateTime(d.Year, d.Month, 1, 0, 0, 0);

I would have suggested to subclass that control and override those event handlers with code to preserve the day, and handle the cases where the target month has less days than the current month, but I'm afraid that the Calendar instance used by the DatePicker implementation is not accessible from user code. The DatePicker also does not expose those internal events as far as I could see.