2014-12-07 101 views
-2

模拟自动售货机,并希望将产品数量文本框设置为只接受大于0的值。当我输入-1时,我的程序接受此值并显示这其中我不want.can有人帮助,请将输入数据验证添加为只接受大于0的整数值

代码:

//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

您可能因为没有明确提出问题而拒绝投票 – logixologist 2014-12-07 04:01:37

+1

您的代码不包含指定的数据范围验证(> 0);您必须添加该行并在验证失败时抛出ArgumentException。最好的问候, – 2014-12-07 04:01:49

+0

你是否检查输入的值是否大于0? – logixologist 2014-12-07 04:02:43

回答

0

您应该添加量范围验证,按您的规格 - 看到如下所示的代码片段:

//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方法可以实现进一步的性能优化,但是考虑到相对简单的任务,与这种情况相关的两种解决方案都足以达到目的。作为一般的建议,考虑增加输入验证,以控制事件(例如TextBox.TextChanged +=(s,e)=>{ // validation}; 此外,有关你的情况,考虑对象设置为null在验证失败。

希望这将有助于。最好的问候,

+1

Alex,我喜欢你正在验证的事实,但这是一个可怕的想法......使用Try/Catch并为val抛出错误idation。 尝试抓住永远不应该,恕我直言,被用于验证。它应该用于捕获未处理的异常。 – logixologist 2014-12-07 04:08:08

+0

我修改了答案,谢谢。 – 2014-12-07 04:15:20

+1

Try/Catch是开发人员和API设计人员在开发流程中沟通并捕获异常情况的一种机制。它们不适用于数据验证,不应该以这种方式使用它们。仅仅为了数据验证的目的而抛出和捕获异常是缓慢且昂贵的。 – Murven 2014-12-07 04:18:17