daa daa
daa daa

Reputation: 141

TextBox with comma into sql

I'm trying to insert a textbox with a decimal value into sql. If the textbox will contain dot then it works fine, but what if someone will use comma instead of dot? How can i catch both situations?

Example i want to insert value 1,9

con.Open();
SqlCommand cmd = new SqlCommand("Insert into inventory (price) values ('" + Convert.ToDecimal(textBox1.Text) + "')", con);
cmd.ExecuteNonQuery();
con.Close();

I'm taking Error converting data type varchar to float. I need whatever user will put in textbox, dot or comma to convert it as float value into sql

Upvotes: 0

Views: 155

Answers (1)

Dan Guzman
Dan Guzman

Reputation: 46203

If you don't know whether the user will use a comma or period as the decimal separator (unaware of their culture), you could try both. Below is a parameterized example.

    decimal decimalValue;

    NumberFormatInfo formatWithPeriod = CultureInfo.InvariantCulture.NumberFormat;
    if (!Decimal.TryParse(textBox.Text, NumberStyles.AllowDecimalPoint, formatWithPeriod, out decimalValue))
    {
        NumberFormatInfo formatWithComma = (NumberFormatInfo)formatWithPeriod.Clone();
        formatWithComma.NumberDecimalSeparator = ",";
        if (!Decimal.TryParse(textBox.Text, NumberStyles.AllowDecimalPoint, formatWithComma, out decimalValue))
        {
            //error here
            return;
        }
    }

    con.Open();
    SqlCommand cmd = new SqlCommand("Insert into inventory (price) values (@price);", con);
    var priceParameter = cmd.Parameters.Add("@price", SqlDbType.Decimal);
    priceParameter.Precision = 18;
    priceParameter.Scale = 2;
    priceParameter.Value = decimalValue;
    cmd.ExecuteNonQuery();
    con.Close();

Upvotes: 1

Related Questions