2014-12-07 49 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