It turns out that TextBox1.Text
must have a value that can not be converted to number . Try to validate this, print it on the screen or in the console before trying to convert it to number.
My guess is that there is a blank at the beginning or the end.
To avoid this kind of thing, you can use a TryParse
. The TryParse
returns true
if the conversion was successful and false
otherwise.
See an example.
int valorDigitado;
bool conversaoSucedida = int.TryParse(TextBox1.Text, out valorDigitado);
if(!conversaoSucedida)
{
MessageBox.Show("Valor digitado é inválido");
return;
}
double morte; // = cálculo;
It might also be interesting to use other approaches, some in conjunction with this one, but you can not give a lot of hint without having more details of what you intend to do. Already, it can be a good idea to use a TrimStart()
and / or TrimEnd()
to remove the spaces at the beginning and end of string
. Depending on the context, you can use a regex and take only the numeric part of the string
(I think a little exaggeration, but everything depends on context) or make a component that only accepts numbers as input ... Anyway, there are infinite possibilities .
About the error message
The error message in Portuguese is a bit of an idiot and the worst of it is that it has been this way since I know .NET.
The message:
The input string was not in an incorrect format
In fact, it should be
The input string was not in a correct format
The original message is:
Input string was not in a correct format