传递null值时,System.DBNull异常 [英] System.DBNull exception when passing null value

查看:50
本文介绍了传递null值时,System.DBNull异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,如果字符串为空,我试图传递null值.

但这会引发异常.有人帮助我在这里缺少什么吗?

Here is my code, i was trying to pass null value if the string is empty.

But it throws exception.any one help me what am missing here ?

DateTime strDateTime = System.Convert.ToDateTime(item.TerminationDate);
string conv=System.Convert.ToString (strDateTime);
DateTime dateToSave;
dateToSave = DateTime.Parse(conv);

 if (!String.IsNullOrEmpty(conv))
     dateToSave = DateTime.Parse(conv);
else
    dateToSave= System.DBNull.Value



[edit]已添加代码块-OriginalGriff [/edit]



[edit]Code block added - OriginalGriff[/edit]

推荐答案

我真的并不感到惊讶.
1)您将字符串转换为DateTime:
I''m not that surprised, really.
1) You convert from a string to a DateTime:
DateTime strDateTime = System.Convert.ToDateTime(item.TerminationDate);


2)您将DateTime转换回字符串:


2) You convert the DateTime back to a string:

string conv=System.Convert.ToString (strDateTime);


3)您将字符串转换回DateTime:


3) You convert the string back to a DateTime:

dateToSave = DateTime.Parse(conv);


4)然后测试您刚才使用的字符串是否会引发异常:


4) You then test if the string you just used would have thrown an exception:

if (!String.IsNullOrEmpty(conv))


5)无法编译:


5) This won''t compile:

dateToSave = System.DBNull.Value



也许您需要考虑一下,因为这里存在许多问题:

1)如果item.TerminationDate不是有效日期,它可能会失败
2)您不需要继续在字符串和DateTime之间进行传输.
3)您应该在使用前而不是之后进行检查.
4)您只能将DateTime值分配给DateTime.

您实际上想做什么?



Perhaps you need to think this a bit, as there are a number of problems here:

1) It could fail if the item.TerminationDate is not a valid date
2) You don''t need to keep transfering between strings and DateTime.
3) You should check before you use, rather than after.
4) You can only assign DateTime values to a DateTime.

What are you actually trying to do?


如果我是您,我会这样做:
I''d do this if I were you:
string strDateTime = item.TerminationDate.ToString();
DateTime dateToSave;
if (!string.IsNullOrEmpty(strDateTime))
{
    dateToSave = Convert.ToDateTime(strDateTime)
}


这样,我不必担心将null值分配给DateTime变量.您应该包含else { }构造,以添加在string变量为null时将执行的代码.


That way I wouldn''t have to worry about assigning a null value to the DateTime variable. You should include the else { } construct to add code that will execute if the string variable is null.


DateTime数据类型不支持DBNull值.您需要将dateToSave更改为Object,或创建一个布尔值标志以说明是否已填充
DateTime data types don''t support DBNull values. You need to change your dateToSave to an Object, or create a Boolean flag to say if it''s populated or not


这篇关于传递null值时,System.DBNull异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆