4

I haven't been able to find the right solution for this issue, and I know it's so simple but I have forgotten how to do it. I have a form with one textfield field that is not required by the user to fill in. I want to insert NULL into the database, not a 0 which is it currently doing. I am not sure what I am missing, though. The textbox is named taxRateTxt, and what I have currently does not work for me:

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();
    }

What am I missing here?

3
  • Do you have a default value for the column? Commented Feb 7, 2014 at 15:01
  • Your statement taxStr = DBNull.Value; should give you a compile time error. Commented Feb 7, 2014 at 15:01
  • if you need to insert null ,just omit that field from you Insert SQL Script(if there is no default value for that field).Can you add your insert script to the post? Commented Feb 7, 2014 at 15:02

2 Answers 2

23

Remove this block of code

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

}

and change this

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

to this

cmd.Parameters.Add(new SqlParameter("@TaxRate", string.IsNullOrEmpty(taxRateTxt.Text) ? (object)DBNull.Value : taxRateTxt.Text));
Sign up to request clarification or add additional context in comments.

1 Comment

Love the casting DBNull.Value to object trick. Saves so much time -)
4

Passing in Convert.DBNull (or DBNull.Value) will do it.

http://msdn.microsoft.com/en-us/library/system.convert.dbnull(v=vs.110).aspx

Of course, you'll have to check the string value first and then pass that in instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.