I'm trying to Convert the string "5.7" (from a textbox) in to a float like this:
float m = float.Parse(TextBox9.Text);
But I'm getting the following error:
System.FormatException: Input string was not in a correct format.
what is wrong please?
You et the exception, because the text in the TextBox9 does not fit the "country-rules" for a correct decimal number. Usually this happens, if the dot represents a thousand seperator and not the decimal point. Maybe you can use:
float number = float.Parse(TextBox9.Text, CultureInfo.InvariantCulture);
or
float number = float.Parse(TextBox9.Text, Thread.CurrentThread.CurrentUICulture);
To avoid the exception you can use:
float number;
if (!float.TryParse(TextBox9.Text, out number))
MessageBox.Show("Input must be a decimal number.");
Thread.CurrentThread.CurrentUICulture used by default. Avoiding exception not very good approachTextBox9. Additionally the requirement is to input a number. In this case for me the input of a non-number into the textbox is not an exceptional behaviour. Thats why I would avoid the exception.6.7 and 6,7 as the same thing or if they mean different things, and if it should mean different things in cultures that uses different decimal points and thousand separators. Since the OP seems to be clueless to these nuances, making him aware of this is also the right thing to do.
textboxholdCultureyou have? It possible your current culture have different decimal separator characterfloat m = float.Parse(TextBox9.Text, CultureInfo.InvariantCulture);CultureInfo.InvariantCulturehas decimal separator set to.(dot)