[W#WPF应用程序在文本框为空时崩溃

问题描述 投票:0回答:1

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

但是,当文本框为空并且我按下计算按钮时,应用程序将崩溃。是否也有办法为此设置故障保护?预先感谢!

c# wpf textbox field
1个回答
0
投票

我将改用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://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

可能还有其他方法,但这是快速,简单的,您可以输出非常冗长的错误。

Groeten成功实现了我的锁定项目。

© www.soinside.com 2019 - 2024. All rights reserved.