我一直无法为这个问题找到合适的解决方案,我知道这很简单,但我忘记了怎么做.我有一个带有一个textfield字段的表单,用户不需要填写.我想在数据库中插入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(); }
我在这里错过了什么?
解决方法
删除这段代码
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));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。