我试图使我的代码尽可能紧凑。
使用 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;
}
}
}
谢谢