我一直没有找到解决这个问题的正确方法,虽然它很简单但我已经忘记了如何做。我有一个表单,其中有一个文本字段是用户不需要填写的。我想要将NULL插入到数据库中,而不是当前正在执行的0。虽然我不确定我缺少什么,但文本框的名称为taxRateTxt
,而我目前的方法对我来说不起作用:
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();
}
我这里缺少什么?
taxStr = DBNull.Value;
应该会导致编译时错误。 - Habib