[英]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. 场景:主窗口和子窗口,mainWindowButton打开子窗口,用户输入信息,当用户输入信息时,子窗口关闭,并在主窗口中相应地显示一个矩形。 Everything works!
一切正常! But when i click on the child window's "x" to close the window manually it shows me this error, only then!
但是,当我单击子窗口的“ x”以手动关闭窗口时,仅向我显示此错误! 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 所有代码都在MainWindowButton_ClickEvent中
It is possible the user does not enter an integer into q.textBoxNumberOfEmployees
so you need to handle that. 用户可能没有在
q.textBoxNumberOfEmployees
输入整数,因此您需要进行处理。
Approach 1 方法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 方法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: 为了回应我对您的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.