【问题标题】:C# WPF Application crashes when textboxes are empty [closed]文本框为空时 C# WPF 应用程序崩溃 [关闭]
【发布时间】:2020-05-08 18:40:43
【问题描述】:

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

但每当文本框为空并且我按下计算按钮时,应用程序就会崩溃。有没有办法为此做一个故障保险?提前致谢!

【问题讨论】:

  • “崩溃”意味着代码的某些部分产生了异常。如果您在调试器下运行您的应用程序,您将看到它是哪个异常以及它发生的确切位置。
  • 这是异常的描述:在 mscorlib.dll 中发生类型为“System.FormatException”的未处理异常输入字符串格式不正确。
  • 顺便说一句:All(char.IsDigit) 将返回一个空字符串 true,这可能不是您对代码的期望。
  • 有没有办法让它在使用空字符串时返回false?
  • 当然要加上!string.IsNullOrEmpty(this.lengteBox.Text)等条件。

标签: c# wpf textbox field


【解决方案1】:

我会改用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

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

【讨论】:

    猜你喜欢
    • 2017-07-27
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    相关资源
    最近更新 更多