我在代码隐藏形式中得到了这个小代码块:
using (SqlConnection connection1 = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand("usp_select_claim_id_MERGE", connection1))
{
cmd.CommandType = CommandType.StoredProcedure;
connection1.Open();
{
using (SqlDataReader DT = cmd.ExecuteReader())
{
//Format the Orig Open Date to strip off the time and just leave the date
if ((DT["Orig_Open_Date"]) == null)
{
OrigOpenDt = Convert.ToDateTime("1/1/1900");
OrigOpenDt2 = "";
}
else
{
OrigOpenDt = Convert.ToDateTime(DT["Orig_Open_Date"]);
OrigOpenDt2 = OrigOpenDt.ToString("MM/dd/yyyy");
}
当它命中IF语句时,它告诉我它是错误的,所以代码跳转到“else”语句。但是,当我查看相关记录中的SQL Server表时,它看起来像这样(我实际上只是看下面图像中的第一条记录):
在我看来,像Orig_Open_Date(一直到右边的列)中都有NULL。
如果我抓取一条记录,其中Orig_Open_Date中确实有一个日期,它可以正常工作。如果没有日期,它仍然会尝试运行“else”语句,因此我的“if”语句必定是错误的。
不可否认,我是C#n00b。我在这里做错了什么?
答案 0 :(得分:4)
尝试DBNull.Value
if(value == DBNull.Value)
答案 1 :(得分:0)
您也可以在SQL语句中执行此操作:
Select ISNULL(Orig_Open_Date,'1/1/1900') as Orig_Open_Date
答案 2 :(得分:0)
您收到空值的原因是读者从数据库返回的空值。我经常遇到这个问题,现在我总是检查DBNull.value。
例如:
db.GetCommand().CommandText = "SELECT * FROM EMPLOYE";
IDataReader reader = db.GetCommand().ExecuteReader();
if(reader.Read())
{
if(reader["HierdDate"] == DBNull.Value)
// Do that
else
//Do this
}
检查DataReader可以返回的DBNull值总是一件好事。