如何在c#new技术中检查dbnull的datetime? [英] how to check dbnull for datetime in c# new technique ?
问题描述
Hii,
Hii ,
Employee objEmployee = new Employee()
{
EmployeeId = Convert.ToInt32(objReader["EmployeeId"]),
Name = objReader["Name"].ToString(),
Gender = objReader["Gender"].ToString(),
City = objReader["City"].ToString(),
if(! objReader["DateOfBirth"] is DBNull)
{
DateOfBirth = Convert.ToDateTime(objReader["DateOfBirth"])
}
};
我正在尝试dbnull我的出生日期属性,
我设置我的属性的方式是按照新的方式,请在此建议我..
I am trying to dbnull for my dateof birth property ,
The way i am setting my properties is as per new way , please suggest me in this ..
推荐答案
if (! DBNull.Value.Equals(row[fieldName]))
return (string) row[fieldName] + " ";
else
return String.Empty;
浏览 DBNull.Value字段 [ ^ ]。
如果不能使用在对象初始值设定项中,
http:// msdn.microsoft.com/en-us/library/bb384062.aspx [ ^ ]
但你可以使用三元运算符。
http://msdn.microsoft.com/en-us/library/ ty67wk28.aspx [ ^ ]
当你可以施放时不要使用转换。类似地,您可以转换字符串值:
You can't use anif
in an object initializer,
http://msdn.microsoft.com/en-us/library/bb384062.aspx[^]
but you can use the ternary operator.
http://msdn.microsoft.com/en-us/library/ty67wk28.aspx[^]
Don't use Convert when you can cast. Similarly, you can cast the string values:
Name = (string) objReader["Name"]
您的测试错误。您可以测试 DBNull.Value
DateOfBirth是什么类型的?它是可以为空的DateTime吗?
You have the wrong test. You can test for DBNull.Value
What type is DateOfBirth? Is it a nullable DateTime?
DateOfBirth = objReader["DateOfBirth"]==DBNull.Value ? null : (DateTime) objReader["DateOfBirth"]
如果你把日期存储为一个字符串(你真的不应该),那么使用TryParse(或类似的) )
http://msdn.microsoft.com/en-us/library/ch92fbc1(v=vs.110).aspx [ ^ ]
If you are storing the date as a string (and you really shouldn't), then use TryParse (or similar)
http://msdn.microsoft.com/en-us/library/ch92fbc1(v=vs.110).aspx[^]
DateTime dob ;
...
DateOfBirth = objReader["DateOfBirth"]==DBNull.Value ||
!DateTime.TryParse ( objReader["DateOfBirth"], out dob ) ? null : dob
这篇关于如何在c#new技术中检查dbnull的datetime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!