2014-02-07 38 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

这对我有效。谢谢! –

相关问题