[英]null DateTime from excel sheet adding to database using C#
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.
它来自excel文件(使用Aspose)为null,但DateTime除外。 I added the DateTime ?
我添加了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 尝试1
EnterDate = Convert.ToDateTime(dr["EnterDate"]);
EnterDate = (EnterDate.HasValue) ? EnterDate : DateTime.Now;
Try 2 试试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?
您不能将null转换为
DateTime?
to solve the problem, you have to define the variable as being of type DateTime?
要解决该问题,您必须将变量定义为
DateTime?
类型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. 我从
Excel Sheet
中将数据作为字符串,然后控制它是否为空。 If its I set it to null
else I converted it to DateTime as below. 如果将其设置为
null
则将其转换为DateTime,如下所示。 This avoids me from exception that can happen in Convert
function. 这避免了我在
Convert
函数中可能发生的异常。
StartDate = dr[2].ToString().Trim();
if (StartDate != "")
r.Data.StartDate = Convert.ToDateTime(StartDate);
else
r.Data.StartDate = null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.