DateTimePicker and DateTime.MaxValue

For some unknown reason, the Winforms DateTimePicker control does not allow for dates higher than 9998-12-31. Trying to set the DateTimePicker MaxDate property of DateTime.MaxValue will result in an exception. This is a limitation imposed by the component itself.

Good news is there is a small trick to overcome this limitation. It requires to update the static MaxDateTime property to an arbitrary value (DateTime.MaxValue in our case). Lets put up some reflection code for that purpose:

var dtpType = typeof(DateTimePicker);
var field = dtpType.GetField("MaxDateTime"BindingFlags.Public | BindingFlags.Static);
if (field != null)
{
    field.SetValue(new DateTimePicker(), DateTime.MaxValue);
}

Just copy and paste this code into the startup method. Basically it needs to run before any DateTimePicker control is created.

Please note that running this code can have side effects because it is not known why this limitation is present in the first place. Use it at your own risk.

Popular posts from this blog

Handling exceptions the right way in WCF (part 2)

Adding a delay before processing Textbox events

Change the deployment URL of a ClickOnce application