DateTime,类型为“ System.InvalidOperationException”的异常 [英] DateTime, an exception of type 'System.InvalidOperationException'

查看:310
本文介绍了DateTime,类型为“ System.InvalidOperationException”的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的TimePicker遇到此问题。
当我没有选择任何时间时,我会收到此错误:

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'

此行发生异常的地方:

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.

这是整个代码:

 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);


推荐答案

嗯,您应该检查一下 startBreak1中的内容。可能是从startBreak1.Value到DateTime的强制转换导致了此错误。

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

Break1S有一个值,但这与问题无关,因为ir是0001年1月1日-任何DateTime结构的初始值。问题很可能是由于强制转换(如果startBreak1.Value是DateTime?或Nullable,那么您的选择是使用另一种类型的构造,即

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;

请注意,您可以使用DateTime.Now,DateTime.Today,DateTime.Now.AddMinutes(-10)或其他任何您认为适当的默认值(如果startBreak1.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. )

这篇关于DateTime,类型为“ System.InvalidOperationException”的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆