添加输入数据验证以仅接受大于0的整数值

时间:2014-12-07 03:58:32

标签: c# winforms validation try-catch tryparse

我正在模拟自动售货机,并希望将产品数量文本框设置为仅接受大于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");
     }

1 个答案:

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

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