Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am trying to use a DateTimePicker in a Windows form, and have come across some odd behavior. I have the Format set to "Short", and ShowUpDown set to "True", but otherwise there is nothing special set on the control. My testers have reported to me, and I've confirmed, that if they edit one field, segment, datepart, whatever its called, of a MM/DD/YYYY date, that same field will be highlighted and have the focus any time the focus comes back around to that DateTemePicker control, even on new records (where the Value property has been changed). For example:

1) I originally have the date "2/13/2011";
2) I change that date to "2/12/2011", and Tab out without moving to the "2011" part;
3) Save the record;
4) Add a new record, which resets the Value to "2/13/2011";
5) Tab into the control;
6) The "13" (date) part of the field is highlighted and has focus.

I found here http://www.eggheadcafe.com/software/aspnet/31385087/location-in-datetimepicker.aspx[^] that DateTimePicker does not expose the location of what is highlighted, so that is not something I can programmatically set. This is fine, except that I really want the focus to be on the month part rather than whatever happened to have been edited last.

Any suggestions on how to do this other than by disposing of and reinstantiating the control?
Posted

1 solution

I have run into this in the past. While you can send mouse or keyboard messages to resolve this, it's a little easier if you don't mind using what is an ugly hack, but one that works.

C#
var format = dateTimePicker1.Format;
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.Format = format;


The trick is to force the control to internally reset itself by changing the Format and then setting it back to what it was. The code above assumes that it is something other than Custom.
 
Share this answer
 
Comments
Espen Harlinn 14-Feb-11 17:29pm    
My 5, nice to know - my usual solution is to use the DevExpress.XtraEditors - so I usually don't experience this problem at all :)
Nish Nishant 14-Feb-11 17:32pm    
Yeah, that would work too :-)

I haven't seen a single major Winforms product that does not use DevEx. They seem to be a total monopoly for Winforms!
Espen Harlinn 14-Feb-11 18:12pm    
Well, questions like this shows some of the reasons for using their products :)
85gator 15-Feb-11 8:28am    
That resolved my issue. Thanks for the help!
Nish Nishant 15-Feb-11 8:37am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900