我正在创建一个比萨菜单,并且在Windows窗体应用程序中有我的数值对象,当我将Cheese Pizza Pizza的numericUpDown值更改为1时,它会在总账单标签中输出3.50英镑,但是当我将其中的numericUpDown值更改为火腿披萨,它将标签中的文本替换为£4.20。当我有1x芝士披萨和1x火腿披萨时,我该如何将总计加起来以使£7.70成为1x芝士披萨和1x火腿披萨

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

最佳答案

这两个事件应调用一个通用方法,该方法重新计算两个数量的总数

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

10-05 18:04