繁体   English   中英

退出应用程序后,类型为'System.FormatException'的未处理异常

[英]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));
        }

场景:主窗口和子窗口,mainWindowButton打开子窗口,用户输入信息,当用户输入信息时,子窗口关闭,并在主窗口中相应地显示一个矩形。 一切正常! 但是,当我单击子窗口的“ x”以手动关闭窗口时,仅向我显示此错误! 我在先前的问题中寻找了与我类似的答案,但是没有一个确切的问题。

所有代码都在MainWindowButton_ClickEvent中

用户可能没有在q.textBoxNumberOfEmployees输入整数,因此您需要进行处理。

方法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

方法2

答案所示,仅允许用户在文本框中输入数字。 由于您在多个位置进行了检查,因此我将为此创建一个用户控件,以便仅允许数字。 然后在每个需要的地方使用该用户控件。 取决于您要使用哪种方法。

为了回应我对您的OP所做的评论,我将尝试为您写出它,实际上使用起来非常简单:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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