programmernovice
programmernovice

Reputation: 3941

How to set a dateTimePicker value to DateTime.MaxValue

This generates an error at runtime:

dateTimePicker.Value = DateTime.MaxValue;

Upvotes: 10

Views: 8211

Answers (4)

Johann Blais
Johann Blais

Reputation: 9469

Yes you can, but it is quite dirty (use it at your own risk). Basically, it overwrites the MaxValue defined in the DateTimePicker with the MaxValue from the DateTime object.

Paste this code into the Main (or any method run during startup):

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

Upvotes: 2

Phaedrus
Phaedrus

Reputation: 8421

You need to use the DateTimePicker.MaximumDateTime property. The maximum value allowable for the datetime picker is 31/12/9998, as represented by DateTimePicker.MaximumDateTime. Whereas the value of DateTime.MaxValue is 31/12/9999.

Upvotes: 3

SLaks
SLaks

Reputation: 887469

You can't.

The maximum date supported by DateTimePicker is DateTimePicker.MaximumDateTime, which is 12/31/9998; DateTime.MaxValue is 12/31/9999 23:59:59, which is one year and one day later.

Can you use that DateTimePicker.MaximumDateTime instead of DateTime.MaxValue?

Upvotes: 8

Dabblernl
Dabblernl

Reputation: 16121

Perhaps this is helpful:

The value of this constant is equivalent to 23:59:59.9999999, December 31, 9999, exactly one 100-nanosecond tick before 00:00:00, January 1, 10000.

Some calendars, such as the UmAlQuraCalendar, support an upper date range that is earlier than MaxValue. In these cases, trying to access MaxValue in variable assignments or formatting and parsing operations can throw an ArgumentOutOfRangeException. Rather than retrieving the value of DateTime..::.MaxValue, you can retrieve the value of the specified culture's latest valid date value from the System.Globalization.CultureInfo.DateTimeFormat.Calendar.MaxSupportedDateTime property.

blatantly copied from msdn

Upvotes: 0

Related Questions