2013-03-22 57 views
0

我使用VS 2012的一部分,Windows窗體項目,C#看看輸入文本框的值存在作爲數組

我有一個產品叫products[],我在我的項目中的XML文件中獲取的數組。用戶將使用數字鍵盤輸入產品ID(4位數字,只讀文本框),然後通過products[]進行搜索以查找與ID匹配的價格並向用戶返回其「更改」。如何讓用戶輸入無效的產品ID或輸入ID後點擊「購買」告訴他們「錯誤此ID不存在」。這是我購買按鈕的代碼,在用戶輸入他們的「錢」併爲產品做出4位數選擇後。

CoinChange是給我們的銀行DLL中的類,它有一個名爲TotalChange方法,該方法在兩個參數吐回的變化,decimal productpricedecimal amountDeposited

private void btnPurchase_Click(object sender, EventArgs e) 
{ 
    TextReader reader = null; 
    decimal productprice; 
    decimal amountDeposited = Convert.ToDecimal(txtDepositAmount.Text); 
    int productChoice = Convert.ToInt16(txtChoice.Text); 
    XmlSerializer serializer = new XmlSerializer(typeof(Product[])); 
    reader = new StreamReader("../../XML/Drinks.xml"); 
    Product[] products = (Product[])serializer.Deserialize(reader); 
    for (int x = 0; x < products.Length; x++) 
    { 
     if (products[x].productID == productChoice) 
     { 
      productprice = products[x].price; 
      CoinChange CC = Service.TotalChange(productprice, amountDeposited); 
      MessageBox.Show("Refund amount:" + "\r\n" + "Nickel: " + CC.Nickel.ToString() + "\r\n" + "Dime: " + 
       CC.Dime.ToString() + "\r\n" + "Quarter: " + CC.Quarter.ToString()); 

      break; 
     } 
    } 
} 

請不要喊叫在我看來,如果這種格式不正確,我是新手,我會解決它,讓我知道需要解決的問題。謝謝!

回答

1
for (int x = 0; x < products.Length; x++) 
    { 
     if (products[x].productID == productChoice) 
     { 
      productprice = products[x].price; 
      CoinChange CC = Service.TotalChange(productprice, amountDeposited); 
      MessageBox.Show("Refund amount:" + "\r\n" + "Nickel: " + CC.Nickel.ToString() + "\r\n" + "Dime: " + 
          CC.Dime.ToString() + "\r\n" + "Quarter: " + CC.Quarter.ToString()); 
      return; // Found and handled the product 
     } 
    } 
    // If we get here none of the products matched 
    MessageBox.Show("Invalid product ID. Please check your catalog and try again."); 
+0

太棒了,謝謝。出於某種原因,我只是沒有把它看作簡單的哈哈。再次感謝。 – BackDoorNoBaby 2013-03-22 23:28:09