Pregunta

I'm using TextChanged Event in order to calculate two textboxes and show the result in a third textbox. However, it already works but when the value of any of the two textboxes changes I got FormatException 'Input string was not in a correct format'. Here is my code:

private void txtCustActualDefect_TextChanged(object sender, EventArgs e)
{
    int TargetDefect = int.Parse(txtCustTargetDfect.Text);
    int ActualDefect = int.Parse(txtCustActualDefect.Text);

    decimal Per = ((decimal)ActualDefect / (decimal)TargetDefect) * 100;
    txtCustPercentageDefect.Text = Per.ToString();
}

I know that when altering the value it takes the value of Zero, but how can I prevent that any thoughts I would appreciated

¿Fue útil?

Solución

You could use int.TryParse. Which would return true if the cast passes.

                 int TargetDefect;
                 int.TryParse(txtCustTargetDfect.Text, out TargetDefect);

                 int ActualDefect;
                 int.TryParse(txtCustActualDefect.Text, out ActualDefect);

A more safer implementation could be:

            int TargetDefect;
            int ActualDefect;

            if(int.TryParse(txtCustTargetDfect.Text, out TargetDefect) && int.TryParse(txtCustActualDefect.Text, out ActualDefect))
            {
                decimal Per = ((decimal) ActualDefect/(decimal) TargetDefect)*100;
                txtCustPercentageDefect.Text = Per.ToString();
            }

Otros consejos

The value of a TextBox's Text property can never be null, but it can be String.Empty, i.e. an empty string.

Parsing an empty string or any other string that cannot read as an integer will result in an exception thrown.

You can use TryParse to try and parse the string without the chance of an exception:

int actualDefect;
bool result = int.TryParse(txtCustActualDefect.Text, out actualDefect);

If result is true, the conversion succeeded; if false it failed:

if (result)
{
    // The conversion was succesful
}
else
{
    // The conversion has failed
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top