[英]leave datetime picker returns 1 / 1 / 0001 12:00:00 AM in c#
I define this in my class 我在课堂上定义
public DateTime? LineCheckSubmitDateTime { set; get; }
I need to initialize this variable using my gridview
我需要使用
gridview
初始化此变量
But sometimes i need to leave this value to be null ,But when i leave it it returns 1 / 1 / 0001 12:00:00 AM
但是有时我需要将此值保留为null,但是当我将其保留时,它将返回
1 / 1 / 0001 12:00:00 AM
so here is my code : 所以这是我的代码:
newObj.LineCheckSubmitDateTime = (Convert.ToDateTime(gridViewDetails.GetRowCellValue(rowHandle, "LineCheckSubmitDateTime"))==DateTime.Parse("1 / 1 / 0001 12:00:00 AM") ) ? Convert.ToDateTime(gridViewDetails.GetRowCellValue(rowHandle, "LineCheckSubmitDateTime")):null;
So two questions: 有两个问题:
1:this code returns this error : 1:此代码返回此错误:
Severity Code Description Project File Line
Error CS0173 Type of conditional expression cannot be determined because there is no implicit conversion between 'DateTime' and '<null>'
2:do you have better solution? 2:您有更好的解决方案吗?
The error is because you have to explicitly cast at least one of the operand of conditional operator to DateTime?
该错误是因为您必须将条件运算符的至少一个操作数显式转换为
DateTime?
A better way to do it would be to compare it with DateTime.MinValue
instead of converting minimum date string to DateTime
, and also cache the converted value and then use it in the conditional operator instead of converting it twice. 更好的方法是将其与
DateTime.MinValue
进行比较,而不是将最小日期字符串转换为DateTime
,并且还缓存转换后的值,然后在条件运算符中使用它,而不是对其进行两次转换。
var tempDateConverted = Convert.ToDateTime(gridViewDetails.GetRowCellValue(rowHandle, "LineCheckSubmitDateTime"));
newObj.LineCheckSubmitDateTime = tempDateConverted == DateTime.MinValue ?
null : (DateTime?) tempDateConverted;
You can also explicitly cast null
to DateTime?
您还可以将
null
显式转换为DateTime?
in the above statement. 在上述声明中。
I am not sure about the LineCheckSubmitDateTime
control in GridView
, here is a possibility that its value is already a DateTime
object , returned inside an object
. 我不确定
GridView
的LineCheckSubmitDateTime
控件,这很可能是它的值已经是一个DateTime
对象,并在object
内部返回。 You can also try: 您也可以尝试:
object obj = gridViewDetails.GetRowCellValue(rowHandle, "LineCheckSubmitDateTime");
newObj.LineCheckSubmitDateTime = (DateTime?) obj;
With the above code, you don't have to call Convert.ToDateTime
. 使用上面的代码,您不必调用
Convert.ToDateTime
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.