Skip to main content
 首页 » 编程设计

c#之确定日期字段是否包含 NULL 值

2024年02月13日13tuyile006

我有代码隐藏形式的这个小代码块:

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。我在这里做错了什么?

请您参考如下方法:

试试 DBNull.Value

if(value == DBNull.Value)