BackDoorNoBaby
BackDoorNoBaby

Reputation: 1455

See if entered textbox value exists as part of an array

I am using VS 2012, Windows Forms Project, C#

I have an array of products called products[] that I am getting from an XML file in my project. The user will use a keypad of numbers to enter a product ID (4 digits, read-only textbox) and then I search through the products[] to find the price that matches the ID and give the user back their "change". How can I keep the user from inputting an invalid product ID or after they input the ID and click "purchase" tell them something like "ERROR this ID does not exist." Here is my code for the Purchase button, after the user has put in their "money" and made a 4 digit selection for a product.

CoinChange is a class from a DLL given to us for the Bank, it has a method called TotalChange that takes in two arguments to spit back the change, decimal productprice and decimal 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;
        }
    }
}

Please don't yell at me if this is not formatted right, I am new to the site and I will fix it just let me know what needs to be fixed. Thank you!

Upvotes: 0

Views: 149

Answers (1)

j__m
j__m

Reputation: 9645

    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.");

Upvotes: 1

Related Questions