简体   繁体   中英

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

在此处输入图片说明

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

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 :

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?

The error is because you have to explicitly cast at least one of the operand of conditional operator to 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.

var tempDateConverted = Convert.ToDateTime(gridViewDetails.GetRowCellValue(rowHandle, "LineCheckSubmitDateTime"));
 newObj.LineCheckSubmitDateTime = tempDateConverted == DateTime.MinValue ?
                                    null : (DateTime?) tempDateConverted;

You can also explicitly cast null to 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 . 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 .

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