简体   繁体   中英

An unhandled exception of type 'System.FormatException' after exiting the app

 if (int.Parse(q.textBoxNumberOfEmployees.Text) < 15)
        {
            Rect1.Fill = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
        }

scenario: main window and a child window, mainWindowButton opens the child window and the user enters information, when the user enters information the child window closes and in the main window a rectangle shows filled accordingly. Everything works! But when i click on the child window's "x" to close the window manually it shows me this error, only then! I looked for an answer in previous questions similar to mine, but none have the exact problem.

All the code is in the MainWindowButton_ClickEvent

It is possible the user does not enter an integer into q.textBoxNumberOfEmployees so you need to handle that.

Approach 1

var numOfEmployees;

if (!int.TryParse(q.textBoxNumberOfEmployees.Text, out numOfEmployees))
{
    // What do you want to do? The user did not enter an integer.
}

// Proceed normally because user entered integer and it is stored in numOfEmployees

Approach 2

Only allow the user to enter numbers into the textbox as shown in this answer. Since you have that check in multiple places, I would create a user control for this so it allows only numbers. Then use that user control every where it is needed. It is up to you which approach you want to go with.

In response to the comment I made on your OP, I'll try to write it out for you, it's actually pretty simple to use:

    try
    {
        if (int.Parse(q.textBoxNumberOfEmployees.Text) < 15)
        {
            Rect1.Fill = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
        }
    }
    catch(System.FormatException ex) //This code will be executed because a System.FormatException was thrown
    {
        //write the error message to the console (optional)
        Console.WriteLine(ex.Message);

        //You can write whatever code you'd like here to try and combat the error.
        //One possible approach is to just fill Rect1 regardless. Delete the
        //code below if you would not like the exception to fill Rect1
        //if this exception is thrown.

        Rect1.Fill = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM