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

C# WPF Application crashes when textboxes are empty

我使用 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;
    }

然后在您的 'run calculation' 按钮中,您可以这样做;

var errors = CheckFields();

if(errors.Any())
{

   // show a messagebox, see; https://docs.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

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