2013-01-25 61 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