2015-12-03 105 views
-2

我收到此异常时,我的列的数据表中有一个空值。假设我想要允许空值或类似的东西,我该如何解决这个问题?字符串未被识别为有效的日期时间。

字符串未被识别为有效的DateTime。

这是我的代码。

 foreach (DataRow row in ds.Tables[0].Rows) 
       { 
    row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy") 
+ " - " + Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy"); 
    } 

在我ds.Table,这里是我的专栏

---------------------- 
Effective_Period 
--------------------- 
10/2/2012 - 20/3/2012 
--------------------- 

--------------------- 

--------------------- 
+0

当列有'null'时你想要做什么? –

+0

你不能将空列转换为datatime这就是为什么你会得到错误,我建议你更新你的存储过程来处理空值,以便你不会返回任何空值。 – user2705620

+0

可能的重复http://stackoverflow.com/questions/2193012/string-was-not-recognized-as-a-valid-datetime-format-dd-mm-yyyy –

回答

1

可能的解决办法:

foreach (DataRow row in ds.Tables[0].Rows) 
{ 
    DateTime effectiveDateFrom; 
    DateTime effectiveDateTo; 

    if (!DateTime.TryParse(row["Effect_Date_From"], out effectiveDateFrom) 
     effectiveDateFrom = DateTime.MinValue; 

    if (!DateTime.TryParse(row["Effect_Date_To"], out effectiveDateTo) 
     effectiveDateTo = DateTime.MinValue; 

    row["Effective_Period"] = effectiveDateFrom.ToString("dd/MM/yyyy") + " - " + effectiveDateTo.ToString("dd/MM/yyyy"); 
} 
+0

谢谢,这是一个完美的解决方案:) – RedRocket

+0

那么,为什么你删除了回答标志? –

+0

噢,对不起,我按错了按钮,没有意识到这 – RedRocket

0

您可能要反映的DateTime定义你的C#表示可为空的选项:

Nullable<DateTime> value; 
// or 
DateTime? value; 

两种形式是等同的。

Ofcourse,在C#中的值工作时,你必须定义什么就做null,你不能依靠一些魔法null.ToString()为您转换。

您可能还想看看this question。精华:使用row.Field<DateTime?>("Effect_Date_From")从数据行中获得可空的DateTime

0

如果您想允许NULL,请在您的数据库表中将该字段设置为NULLABLE。然后它将允许插入NULL值,而不会有任何问题。另外,如果您希望允许显示某个值,则必须将该字段设置为nvarchar,因为此字段不会被识别为有效DateTime

另一个重要的注意事项是,不是像这样存储,而是可以轻松地为起始时间段创建两个单独的列,并分别在两个值中存储DateTime值。这也可以让您根据所需日期查询数据和过滤数据。

UPDATE:

你也会,如果你传递一个NULL,并使用.ToString()收到此异常。所以请确保你使用.ToString()之前在这里传递一些东西,比如日期或字符串。而在后端,您可以根据需要修改数据类型。

这里要做的一件好事是在使用.ToString()转换之前执行空检查。如果为空,则可以直接通过null,如果不存在,则可以转换该值,然后传递该值。

希望这会有所帮助。

+0

在OP的代码中,他试图对空值进行操作。 ToString()。 – NPToita

0

尝试:

foreach (DataRow row in ds.Tables[0].Rows) 
      { 
       bool fromIsNull = DBNull.Value.Equals(row["Effect_Date_From"]); 
       bool toIsNull = DBNull.Value.Equals(row["Effect_Date_To"]); 
       row["Effective_Period"] = (fromIsNull ? string.Empty : Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy")) 
        + (fromIsNull || toIsNull ? string.Empty : " - ") 
        + (toIsNull ? string.Empty : Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy")); 
      } 

更新的代码,以适应你的最后评论。这就是你如何隐藏/显示“ - ”。但这完全取决于你如何处理案件。

+0

您好我已经试过你的方法,它说不能转换字符串中的代码'Convert.ToDateTime该块为bool(行[“Effect_Date_From”]。的ToString())。 ToString(“dd/MM/yyyy”)+“ - ”+ DBNull.Value.Equals(行[“Effect_Date_To”])' – RedRocket

+0

更新了代码部分。我错过了操作优先级的几个括号。 – NPToita

+0

我明白了,谢谢你的帮助。见基斯为正确答案:) – RedRocket

0

Null没有ToString()函数,所以如果你期望结果为null,你必须确保你不会调用它的函数。

相关问题