if (int.Parse(q.textBoxNumberOfEmployees.Text) < 15)
{
Rect1.Fill = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
}
场景:主窗口和子窗口,mainWindowButton打开子窗口,用户输入信息,当用户输入子窗口关闭的信息时,在主窗口中,矩形显示相应的填充。一切正常!
但是,当我点击子窗口的“x”手动关闭窗口时,它只显示这个错误!我在之前的问题中找到了与我类似的答案,但没有一个确切存在问题。
所有代码都在MainWindowButton_ClickEvent
中答案 0 :(得分:2)
用户可能不会在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
仅允许用户在文本框中输入数字,如this answer所示。由于你在多个地方进行了检查,我会为此创建一个用户控件,因此它只允许数字。然后在每个需要的地方使用该用户控件。这取决于你想要采用哪种方法。
答案 1 :(得分:1)
在回复我对您的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));
}