9

我试图使我的代码尽可能紧凑。

使用 Microsoft SQL Server、.NET 2.0

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

LeaseExpiry(datetime, null)

我获取文本框的值并将其转换为日期时间。

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

INSERT_record(leaseExpiry);

我遇到的问题是表单是否已提交并且文本框为空。我得到了这个错误:

字符串未被识别为有效的日期时间。

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

我尝试将变量初始化为 NULL,但在 Visual Studio 中出现错误

DateTime leaseExpiry = null;

无法将 null 转换为“System.DateTime”,因为它是不可为 null 的值类型。

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

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;
         }
     }
}

谢谢

4

4 回答 4

16

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

public string INSERT_record(DateTime? leaseExpirey)
{
    // ...
    command.Parameters.Add("@leaseExpirey", SqlDbType.DateTime);
    command.Parameters["@leaseExpirey"].Value =
                ((object)leaseExpirey) ?? DBNull.Value;
    // ...
}
于 2013-01-25T12:27:03.573 回答
5

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

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

INSERT_record(leaseExpirey);
于 2013-01-25T12:32:18.107 回答
3

你可以使leaseExpirey一个空值DateTime- 即DateTime? leaseExpirey

然后你可以说:

DateTime? leaseExpirey;
if (!string.IsNullOrEmpty(tbLeaseExpiry.Text.Trim()))
    leaseExpirey = Convert.ToDateTime(tbLeaseExpiry.Text);

INSERT_record(leaseExpirey);

您还需要更改INSERT_record以接受DateTime?参数而不是DateTime.

于 2013-01-25T12:28:12.993 回答
0

您应该使用DateTime.MinValue,因为 DateTime 永远不会null

于 2013-01-25T12:38:10.317 回答