【问题标题】:C# - Correct validation for integersC# - 正确验证整数
【发布时间】:2012-03-17 02:26:48
【问题描述】:

我目前正在使用 Windows 窗体构建我的项目,但遇到了一个小“问题”。

我让用户输入一个存储为 int 的小时。我想向用户提供详细的反馈,以便他们在导致错误时确切知道自己做错了什么。

如果没有给出值,则抛出格式异常。 如果给出的不是整数,则会引发格式异常。

这意味着我不能直接告诉用户无法添加新项目,因为 1) 没有值或 2) 不是整数,因为它们都使用相同的异常。

我该如何解决这个问题,最好的解决方案是什么?

非常感谢。

【问题讨论】:

    标签: c# exception integer


    【解决方案1】:

    使用Int32.TryParse 方法并检查返回值。在调用 TryParse 之前,您可以简单地检查是否没有输入任何值。

    这是一个来自 MSDN 的使用示例:

      int number;
      bool result = Int32.TryParse(value, out number);
      if (result)
      {
         Console.WriteLine("Converted '{0}' to {1}.", value, number);         
      }
      else
      {
         if (value == null) value = ""; 
         Console.WriteLine("Attempted conversion of '{0}' failed.", value);
      }
    

    【讨论】:

    • 非常感谢!我使用了一个类似的修改版本,如下所示。
    【解决方案2】:

    一些与您的问题相关的示例代码;特别注意 ValidateData:

    // called from ok button click or similar event
    private void Accept()
    {
       if (!ValidateData())
          return;
    
       SaveData();
       DialogResult = DialogResult.Ok;
       Dispose();
    }
    
    private bool ValidateData()
    {
       int val;
    
       if (string.IsNullOrEmpty(mTextBox.Text))
          return FailValidation("Value can not be empty.", mTextBox);
    
       if (!int.TryParse(mTextBox.Text, out val))
           return FailValidation("Value was not an integer.", mTextBox);
    
       return true;
    }
    
    // do something with the value if you need
    private void SaveData()
    {       
    }
    
    // post a message to the user, and highlight the problematic control
    // always evaluates to false
    private bool FailValidation(string pMessage, Control pControl)
    {
         if (pControl != null)
         {
            pControl.Focus();
            TextBox textBox = pControl as TextBox;
            if (textBox != null)
               textBox.SelectAll();
         }
    
         AlertBox(pMessage);
         return false;
    }
    
    // quick alert message method
    private void AlertBox(string pMessage)
    {
       return MessageBox.Show
       (
          pMessage,          
          Application.ProductName,
          MessageBoxButtons.OK,
          MessageBoxIcon.Exclamation,
          MessageBoxDefaultButton.Button1
       );
    }
    

    【讨论】:

    • 非常感谢!我在 ValidateData 中使用了代码的修改版本。很有魅力!
    【解决方案3】:

    使用 int.TryParse 检查格式,然后在成功的情况下检查整数是否在有效范围内。使用 String.IsNulOrEmpty 检查空字符串。

    【讨论】:

      【解决方案4】:

      如果我可以建议一个可能的替代解决方案...最好的验证是首先防止错误输入。您可以通过使用时间选择器或下拉列表等控件来限制用户可以选择的值吗?下拉列表对于高级用户来说仍然是键盘友好的,对于喜欢鼠标的人来说更容易一些。为所有人赢得胜利。

      【讨论】:

      • 我会使用时间选择器,但从设计方面来看,该元素根本不适合。下拉列表会起作用,但我已经设法为我的文本框实施合适的错误检查。不过,感谢您的回复!
      【解决方案5】:

      这在 Winforms 中得到了很好的支持。使用Validating事件检查入口,ErrorProvider组件报错。一个示例事件处理程序:

          private void textBox1_Validating(object sender, CancelEventArgs e) {
              int hour;
              e.Cancel = true;
              if (textBox1.Text.Length == 0) errorProvider1.SetError(textBox1, "Can't be empty");
              else if (!int.TryParse(textBox1.Text, out hour)) errorProvider1.SetError(textBox1, "Not a number");
              else if (hour < 1) errorProvider1.SetError(textBox1, "Hour too small");
              else if (hour > 24) errorProvider1.SetError(textBox1, "Hour too large");
              else {
                  e.Cancel = false;
                  errorProvider1.SetError(textBox1, "");
              }
          }
      

      然后您只需要检查所有条目是否令人满意。在对话框的 OK 按钮单击事件处理程序中使用 ValidateChildren() 方法:

          private void OKButton_Click(object sender, EventArgs e) {
              if (ValidateChildren()) this.DialogResult = DialogResult.OK;
          }
      

      【讨论】:

        猜你喜欢
        • 2014-01-21
        • 1970-01-01
        • 2014-01-21
        • 2011-09-27
        • 2012-11-02
        • 2012-10-10
        • 1970-01-01
        • 2013-02-26
        • 1970-01-01
        相关资源
        最近更新 更多