Setting an empty string to null for insertion into the database

I could not find the right solution for this problem, and I know that it is so simple, but I forgot how to do it. I have a form with one text field field that the user does not need to fill out. I want to insert NULL into the database, not the 0 that it is currently doing. Although I'm not sure what I am missing. The text field is called taxRateTxt, and what currently does not work for me 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
source share
2 answers

Delete this code block

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 value

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

to that

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

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

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

, , .

+3

All Articles