【问题标题】:Adding Input data validation to accept only integer values greater than 0添加输入数据验证以仅接受大于 0 的整数值
【发布时间】:2014-12-07 03:58:31
【问题描述】:

我正在模拟自动售货机,并希望将产品数量文本框设置为仅接受大于 0 的值。当我输入 -1 时,我的程序接受该值并显示它我不想要。有人可以帮忙吗

代码是:

//create a new Employee object
    try // Exception handling to ensure that incorrect data type cannot be entered into text box creating a new product
       {
            Products newProd = new Products(this.textProdID.Text);
            newProd.ProductName= this.textProdName.Text;
            newProd.ProductQuantity= Convert.ToInt32(this.textProdQuantity.Text);
            newProd.ProductPrice= Convert.ToDouble(this.textProdPrice.Text);
            ProductList.Add(newProd);
            MessageBox.Show(newProd.ProdName + " has been added to the product list");
        }
     catch
     {
        MessageBox.Show("Format entered into text box Is incorrect please check and try again");
     }

【问题讨论】:

  • 你的票数可能会下降,因为你甚至没有明确地提出问题
  • 您的代码不包含指定的数据范围验证(>0);如果验证失败,您必须添加该行并抛出 ArgumentException。最好的问候,
  • 如何检查输入的值是否 > 0?

标签: c# winforms validation try-catch tryparse


【解决方案1】:

您应该根据您的规范添加数量范围验证 - 请参见下面显示的代码 sn-p:

//create a new Employee object
    try // Exception handling to ensure that incorrect data type cannot be entered into text box creating a new product
       {
            Products newProd = new Products(this.textProdID.Text);
            newProd.ProductName= this.textProdName.Text;
            newProd.ProductQuantity= Convert.ToInt32(this.textProdQuantity.Text);
            // add the input range validation 
            if (newProd.ProductQuantity<=0) throw new ArgumentException ("Quantity must be a positive number.");

            newProd.ProductPrice= Convert.ToDouble(this.textProdPrice.Text);
            ProductList.Add(newProd);
            MessageBox.Show(newProd.ProdName + " has been added to the product list");
        }
     catch
     {
        MessageBox.Show("Format entered into text box Is incorrect please check and try again");
     }

另一种解决方案是在验证失败并返回时显示带有错误消息的 MessageBox。进一步的性能优化可以通过使用TryParse()而不是Convert方法来实现,但考虑到相对简单的任务,与这种情况相关的两种解决方案都足以达到目的。作为一般建议,考虑将输入验证添加到 Control 事件(例如 TextBox.TextChanged +=(s,e)=&gt;{ // validation}; 此外,根据您的情况,请考虑在验证失败时将对象设置为 null。

希望这会有所帮助。最好的问候,

【讨论】:

  • Alex,我喜欢你进行验证的事实,但这是一个可怕的想法......使用 Try/Catch 并抛出错误进行验证。恕我直言,Try catch 永远不应该用于验证。它应该用于捕获未处理的异常。
  • Try/Catch 是一种供开发人员和 API 设计人员交流和捕捉开发管道中异常情况的机制。它们不适用于数据验证,不应以这种方式使用。仅出于数据验证目的而抛出和捕获异常既慢又昂贵。
  • 听着,伙计们,这个人要求实际的解决方案,最简单的方法是添加这行代码。还有许多其他方法可以实现目标(最好的方法可能是将验证添加到 .Change 事件上的输入控件),但我不知道其余的代码。他可能应该添加“Finally”语句以将 obj 设置为 null,或者将其添加到 'catch' 块中,但这是一个很长的故事。最好的问候,
猜你喜欢
  • 2020-05-11
  • 2021-10-10
  • 2020-04-15
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 2014-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多