2014-02-07 39 views
3

我一直無法找到適合此問題的正確解決方案,而且我知道這很簡單,但我忘記了如何去做。我有一個表單,其中有一個用戶不需要填寫的文本字段字段。我想將NULL插入到數據庫中,而不是當前正在執行的0。不過,我不確定我錯過了什麼。文本框被命名爲taxRateTxt,和我有什麼當前不爲我工作:我缺少的是在這裏將空字符串設置爲null插入數據庫時​​爲空

try 
{ 
    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString())) 
    { 
     cn.Open(); 
     SqlCommand cmd = new SqlCommand(); 
     cmd.Connection = cn; 

     cmd.Parameters.Add(new SqlParameter("@FIPSCountyCode", countyCodeTxt.Text)); 
     cmd.Parameters.Add(new SqlParameter("@StateCode", stateCodeList.SelectedValue)); 
     cmd.Parameters.Add(new SqlParameter("@CountyName", countyNameTxt.Text)); 

     string taxStr = taxRateTxt.Text; 
     //test for an empty string and set it to db null 
     if (taxStr == String.Empty) 
     { 
      taxStr = DBNull.Value; 

     } 

     cmd.Parameters.Add(new SqlParameter("@TaxRate", taxStr)); 

     if (AddBtn.Visible == true) 

      cmd.CommandText = addQuery; 

     if (EditBtn.Visible == true) 
     { 
      cmd.CommandText = editQuery; 
     } 

     cmd.ExecuteNonQuery(); 
     cn.Close(); 
    } 

+0

您是否有該列的默認值? – abhi

+0

您的語句'taxStr = DBNull.Value;'應該會給您一個編譯時錯誤。 – Habib

+0

如果您需要插入空值,只需從您的字段中刪除插入SQL腳本(如果該字段沒有默認值)。您可以將插入腳本添加到帖子中嗎? –

回答

18

刪除的代碼

string taxStr = taxRateTxt.Text; 
//test for an empty string and set it to db null 
if (taxStr == String.Empty) 
{ 
    taxStr = DBNull.Value; 

} 

該塊並改變此

cmd.Parameters.Add(new SqlParameter("@TaxRate", taxStr)); 

cmd.Parameters.Add(new SqlParameter("@TaxRate", string.IsNullOrEmpty(taxRateTxt.Text) ? (object)DBNull.Value : taxRateTxt.Text)); 
+0

喜歡將'DBNull.Value'強制轉換爲'object'技巧。節省了這麼多時間 - ) –

+0

這對我有效。謝謝! –

相關問題