当文本框为空时,C#WPF应用程序崩溃



我使用C#在WPF中创建了一个应用程序,在这个应用程序中,用户必须填写文本框,并通过单击按钮进行计算。我已经为文本框只能是数字的部分做了故障保护:

private bool allFieldsAreOk()
{
return this.lengteBox.Text.All(char.IsDigit)
&& breedteBox.Text.All(char.IsDigit)
&& cilinderDrukSterkteBox.Text.All(char.IsDigit)
&& vloeigrensStaalBox.Text.All(char.IsDigit)
&& diameterWapeningBox.Text.All(char.IsDigit)
&& diameterBeugelBox.Text.All(char.IsDigit)
&& betondekkingTotWapeningBox.Text.All(char.IsDigit)
&& vloeigrensConstructieStaalBox.Text.All(char.IsDigit);
}

但每当一个文本框为空,我按下计算按钮时,应用程序就会崩溃。有没有什么方法可以为它设置故障保护?提前感谢!

我会使用string.IsNullOrWhiteSpace来检查文本,我会将字段分为不同的检查,这样你就可以知道哪些字段没有填写,并且可以将其传达给用户;

private ICollection<string> CheckFields()
{
var ret = new List<string>();
if(string.IsNullOrWhiteSpace(lengteBox.Text))
{
ret.add($"{nameof(lengteBox)} was null, empty or consisted only of whitespace.");
}
else
{
// So the string is not null, but here we can also check if the value is a valid digit for example 
var isNumeric = int.TryParse(lengteBox.Text, out _);
if(!isNumeric)
ret.add($"{nameof(lengteBox)} could not be parsed as an interger, value: {lengteBox.Text}.");
}
// Add validation to the other boxes etc.

return ret;
}

然后在你的"运行计算"按钮中,你可以做这样的事情;

var errors = CheckFields();
if(errors.Any())
{
// show a messagebox, see; https://learn.microsoft.com/en-us/dotnet/framework/wpf/app-development/dialog-boxes-overview
MessageBox.Show(string.Join(errors, Environment.NewLine));
return;
}
// Found no errors, run the calcuations here! :D

可能还有其他方法,但这是快速、简单的,并且可以输出非常详细的错误。

最新更新