locked
Input string was not in a correct format. RRS feed

  • Question

  •  

    Error:-Input string was not in a correct format.

     

              SqlConnection connection = new SqlConnection();
                connection.ConnectionString = "Data Source = SONUMONU;Initial Catalog=SalesTran;User id=sa;Password=123";
                string str1 = txtCustNam.Text;
                string str2 = txtItem.Text;
                string str3 = txtDis.Text;
                //int str4 = Convert.ToInt32(txtQuantity.Text);
                //int str5 = Convert.ToInt32(txtRate.Text);
                float str4 = Convert.ToSingle(txtQuantity.Text);
                float str5 = Convert.ToSingle(txtRate.Text);
                float str6 = Convert.ToInt32(str4 * str5);

                SqlCommand cmd = new SqlCommand("(insert into Info([Customer Name],[Item Code],Description,Quantity,Rate,Total) Values('" + str1 + "', '" + str2 + "', '" + str3 + "', '" + str4 + "', '" + str5 + "', '" + str6 + "')", connection);
                cmd.ExecuteNonQuery();

    Sunday, April 4, 2010 6:41 AM

Answers

  • What is your used culture? in some cultures '.' character used for floating number e.g. en-US, and in some cultures  ',' character used for floating number e.g. fr-FR. so use Single.Parse instead which allow to you select the culture. e.g.
    //if you are in US
    float str4 = Single.Parse(txtQuantity.Text, CultureInfo.GetCultureInfo("en-US"));
    float str5 = Single.Parse(txtRate.Text, CultureInfo.GetCultureInfo("en-US"));
    float str6 = str4 * str5;
    //if you are in France
    float str4 = Single.Parse(txtQuantity.Text, CultureInfo.GetCultureInfo("fr-FR"));
    float str5 = Single.Parse(txtRate.Text, CultureInfo.GetCultureInfo("fr-FR"));
    float str6 = str4 * str5;

    My Blog - MSDN Complement By Providing Visual C# Walkthroughs and Sample Codes - Founded In February 24, 2010
    • Proposed as answer by Chao Kuo Tuesday, April 6, 2010 1:16 PM
    • Marked as answer by Chao Kuo Friday, April 9, 2010 9:19 AM
    Sunday, April 4, 2010 7:27 AM
  • Always use TryParse. Knowingly raising exception is not a good practice.

    Single singleTemp;
    if (!Single.TryParse(txtWatEver.Text, out singleTemp))
    {
        MessageBox.Show("Value is not in proper format");
    }
    else
    {
        //got the converted value in singleTemp
    }


    Thanks,
    A.m.a.L
    [MVP Visual C#]
    Dot Net Goodies
    Don't hate the hacker, hate the code
    • Proposed as answer by Chao Kuo Tuesday, April 6, 2010 1:16 PM
    • Marked as answer by Chao Kuo Friday, April 9, 2010 9:19 AM
    Sunday, April 4, 2010 8:16 AM

All replies