NumericUpDown Value * price addition

Viewed 116

I am creating a pizza menu and I have numericUpDown objects on my windows form application, at the minute when I change the numericUpDown value of Cheese Pizza to 1, it outputs £3.50 into the total bill label, however when I change the numericUpDown value of Ham Pizza, it will replace the text in the label with £4.20. When I have 1x Cheese Pizza and 1x Ham Pizza, how do I add the totals together to make £7.70 for 1x Cheese Pizza and 1x Ham Pizza

private void NudQuantity1_ValueChanged(object sender, EventArgs e)
{
  if (NudQuantity1.Value == 0)
  {
    gbCheesePizza.Enabled = false;
  }
  else
  {
    gbCheesePizza.Enabled = true;
  }
  Total = Convert.ToDouble(NudQuantity1.Value) * Price_CheesePizza;
  lblTotalBill.Text = String.Format("{0:C}", Total);
}

private void NudQuantity2_ValueChanged(object sender, EventArgs e)
{
  if (NudQuantity2.Value == 0)
  {
    gbHamPizza.Enabled = false;
  }
  else
  {
    gbHamPizza.Enabled = true;
  }
  Total = Convert.ToDouble(NudQuantity2.Value) * Price_HamPizza;
  lblTotalBill.Text = String.Format("{0:C}", Total);
}
2 Answers

Both events should call a common method that recalcs the total for both quantity

private void NudQuantity1_ValueChanged(object sender, EventArgs e)
{

    gbCheesePizza.Enabled = !(NudQuantity1.Value == 0)
    UpdateTotal();

}

private void NudQuantity2_ValueChanged(object sender, EventArgs e)
{
    gbHamPizza.Enabled = !(NudQuantity2.Value == 0)
    UpdateTotal();
}
private void UpdateTotal()
{
    Total = Convert.ToDouble(NudQuantity1.Value) * Price_CheesePizza;
    Total += Convert.ToDouble(NudQuantity2.Value) * Price_HamPizza;
    lblTotalBill.Text = $"{Total:C}";
}

You're overwriting your total each time. Carry it with you as you add items.

Simple example

    Total = Total + (Convert.ToDouble(NudQuantity2.Value) * Price_HamPizza)

Play with it to get it to work no matter the quantity of items or the order in which they are ordered.

Related