I am having an issue with getting a value to pass into this variable. It is null coming from the excel file (using Aspose) but a DateTime doesn't except it. I added the DateTime ? to the variable but that doesn't help. I have tried a few ways that I know but none of them are working for the incoming null value. If the value is null, it has to stay null which the database allows for a null value. Can someone help me get this to work? Is there an easier way to go about this?
Try 1
EnterDate = Convert.ToDateTime(dr["EnterDate"]);
EnterDate = (EnterDate.HasValue) ? EnterDate : DateTime.Now;
Try 2
RepealedDate = (dr["RepealedDate"] == null) ? (DateTime?)null : Convert.ToDateTime(dr["RepealedDate"]);
Replace your second try with this:
DateTime? repealedDate = (dr["RepealedDate"] == null) ?
null : Convert.ToDateTime(dr["RepealedDate"]);
You can't cast null to DateTime?
to solve the problem, you have to define the variable as being of type DateTime?
.
I couldn't find a good solution on web. So I tried to handle it myself. I took data as string from Excel Sheet
and then I controlled if its empty or not. If its I set it to null
else I converted it to DateTime as below. This avoids me from exception that can happen in Convert
function.
StartDate = dr[2].ToString().Trim();
if (StartDate != "")
r.Data.StartDate = Convert.ToDateTime(StartDate);
else
r.Data.StartDate = null;
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.