简体   繁体   中英

DateTime, an exception of type 'System.InvalidOperationException'

Haveing this problem with a TimePicker that i am using. When i dont have selected any time I am getting this error:

An exception of type 'System.InvalidOperationException'

Where the exception occurs is on this line:

DateTime break1S = (DateTime)startBreak1.Value;

The problem is that it sets a default value when you dont set any value in the picker. But why wont it use it? Here is how the local variables look like:

在这里你看到break1S有一个值

You can see that break1S have a value so what is the problem.

Here is the whole code:

 DateTime date = (DateTime)datePicker.Value;
 DateTime start = (DateTime)startingTime.Value;
 DateTime end = (DateTime)endingTime.Value;
 DateTime break1S = (DateTime)startBreak1.Value;
 DateTime break1E = (DateTime)endBreak1.Value;
 DateTime break1S = (DateTime)startBreak1.Value;
 DateTime break1E = (DateTime)endBreak1.Value;
 DateTime break2S = (DateTime)startBreak2.Value;
 DateTime break2E = (DateTime)endBreak2.Value;

            _nestedDateStart = new DateTime(date.Year, date.Month, date.Day, start.Hour, start.Minute, 0);
            _nestedDateEnd = new DateTime(date.Year, date.Month, date.Day, end.Hour, end.Minute, 0);
            _nestedDateStartBreak1 = new DateTime(date.Year, date.Month, date.Day, break1S.Hour, break1S.Minute, 0);
            _nestedDateEndBreak1 = new DateTime(date.Year, date.Month, date.Day, break1E.Hour, break1E.Minute, 0);

Well, You should check, what is in "startBreak1" item during that moment. Possibly a cast from startBreak1.Value to DateTime caused this error.

Break1S has a value, but this has nothing to do with the problem, as ir is January 1st 0001 - an initial value for any DateTime structure. The problem is most probably because of the cast (if startBreak1.Value is DateTime? or Nullable, then Your choise is to use another type of construct instead, ie

DateTime break1S = startBreak1.Value.HasValue ? startBreak1.Value.Value : DateTime.MinValue;

Note that instead of DateTime.MinValue You can use DateTime.Now, DateTime.Today, DateTime.Now.AddMinutes(-10) or anything You think should be appropriate Default if startBreak1.Value has no actual value set. )

I am not an expert of Windows Phone, but it seems to me that the Value property of a TimePicker control is defined as DateTime? meaning a nullable DateTime.
When you try to assign it to a DateTime variable (that cannot accept null values) and the TimePicker is null you get the InvalidOperationException

You could try with

startBreak1  = startBreak1.Value ?? DateTime.MinValue;

Check 'MinDate' and 'MaxDate' properties of your DateTimePicker.

'1/1/0001 12:00:00 AM' might not be falling between them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM