2013-01-25 58 views
7

我试图让我的代码尽可能小巧。SQL Server日期时间接受NULL

使用Microsoft SQL Server,.NET 2.0

我在我的数据库,接受空值

LeaseExpiry(datetime, null) 

我抢的文本框的值,并将其转换为datetime日期字段。

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

INSERT_record(leaseExpiry); 

我遇到的问题是如果提交表单并且文本框为空。我收到此错误:

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

如何设置我的代码了,这样如果文本框为空,排在数据库创建NULL

我已经试过初始化我的变量设置为NULL,但得到一个错误在Visual Studio

DateTime leaseExpiry = null; 

无法将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; 
     } 
    } 
} 

谢谢

+0

应拼写'leaseExpiry'(不'leaseExpirey') - 你在你的代码,这是非常令人困惑的有两个版本。我一直把它固定为'Expiry'。 –

回答

13

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

public string INSERT_record(DateTime? leaseExpirey) 
{ 
    // ... 
    command.Parameters.Add("@leaseExpirey", SqlDbType.DateTime); 
    command.Parameters["@leaseExpirey"].Value = 
       ((object)leaseExpirey) ?? DBNull.Value; 
    // ... 
} 
+0

谢谢你的帮助。 – Scott

2

你可以做leaseExpirey可为空DateTime - 即DateTime? leaseExpirey

然后你就可以说:

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

INSERT_record(leaseExpirey); 

你也只需要修改INSERT_record接受DateTime?参数而不是DateTime

3

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

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

INSERT_record(leaseExpirey); 
+0

谢谢,我也用过这个。 – Scott

0

你应该使用DateTime.MinValue,因为日期时间是永远不会null