Search code examples
c#winformsnumericupdown

NumericUpDown Value * price addition


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);
}

Solution

  • 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}";
    }