SQL Server DateTime接受NULL

Sco*_*ott 8 c# sql-server

我试图让我的代码尽可能紧凑.

使用Microsoft SQL Server,.NET 2.0

我的数据库中有一个日期字段,它接受空值

LeaseExpiry(datetime, null)
Run Code Online (Sandbox Code Playgroud)

我抓住文本框的值并将其转换为datetime.

DateTime leaseExpiry = Convert.ToDateTime(tbLeaseExpiry.Text);

INSERT_record(leaseExpiry);
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是表单是否已提交且文本框为空.我收到此错误:

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

如何设置我的代码,以便如果文本框为空,则在数据库中创建行NULL

我已经尝试将我的变量初始化为NULL但在Visual Studio中出错

DateTime leaseExpiry = null;
Run Code Online (Sandbox Code Playgroud)

无法将null转换为'System.DateTime',因为它是一个不可为空的值类型.

如果有帮助,这是数据访问层

public string INSERT_record(DateTime leaseExpiry)
{
     //Connect to the database and insert a new record 
     string cnn = ConfigurationManager.ConnectionStrings[connname].ConnectionString;

     using (SqlConnection connection = new SqlConnection(cnn))
     {
        string SQL = string.Empty;
        SQL = "INSERT INTO [" + dbname + "].[dbo].[" + tblAllProperties + "] ([LeaseExpiry]) VALUES (@leaseExpiry);

         using (SqlCommand command = new SqlCommand(SQL, connection))
         {
                command.Parameters.Add("@leaseExpiry", SqlDbType.DateTime);
                command.Parameters["@leaseExpiry"].Value = leaseExpiry;
         }

         try
         {
                connection.Open();
                command.ExecuteNonQuery();
                return "Success";
         }
         catch (Exception ex)
         {
                return ex.Message;
         }
     }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Mar*_*ell 15

的确,DateTime不可能null.但是:DateTime?可以.另请注意,在参数上,null表示"不发送"; 你需要:

public string INSERT_record(DateTime? leaseExpirey)
{
    // ...
    command.Parameters.Add("@leaseExpirey", SqlDbType.DateTime);
    command.Parameters["@leaseExpirey"].Value =
                ((object)leaseExpirey) ?? DBNull.Value;
    // ...
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ler 5

尝试使用可为空的 DateTime 和 TryParse()

DateTime? leaseExpirey = null;
DateTime d;
if(DateTime.TryParse(tbLeaseExpiry.Text, out d))
{
    leaseExpirey = d;
}

INSERT_record(leaseExpirey);
Run Code Online (Sandbox Code Playgroud)