Search code examples
c#eventstextchanged

Prevent FormatException when using TextChanged event


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


Solution

  • 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();
                }