C# WinForms中CheckBox与NumericUpDown相乘计算总价问题求助
问题分析与解决方案
原代码核心问题
- 使用
else if处理复选框,导致仅能选中一个选项,无法实现多选累加价格 - 计算乘积的代码仅执行运算但未将结果赋值给变量或更新
txtTotal.Text,因此无任何显示效果 - 验证逻辑与实际处理的控件不匹配(验证检查的是口味复选框,实际计算的是食材复选框)
- 未对
NumericUpDown的输入值做有效性验证(如数量不能为0)
修改后的完整代码
using System; using System.Windows.Forms; namespace IceCreamMelts { public partial class frmMain : Form { public frmMain() { InitializeComponent(); } /// <summary> /// 验证用户输入有效性 /// </summary> /// <returns>验证通过返回true,否则返回false</returns> private bool ValidInputs() { // 至少选中一个食材选项 if (!tomatoes.Checked && !peppers.Checked && !onions.Checked && !potatoes.Checked) { MessageBox.Show("请至少选择一种食材。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } // 验证数量大于0 if (numericUpDown1.Value <= 0) { MessageBox.Show("数量必须大于0。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } private void btnOrderNow_Click(object sender, EventArgs e) { if (ValidInputs()) { double totalBasePrice = 0.0; // 累加所有选中食材的基础价格 if (tomatoes.Checked) totalBasePrice += 1.91; if (peppers.Checked) totalBasePrice += 2.32; if (onions.Checked) totalBasePrice += 1.05; if (potatoes.Checked) totalBasePrice += 1.50; // 累加选中食材的配料费用(若不需要可删除此段) if (tomatoes.Checked) totalBasePrice += 0.50; if (peppers.Checked) totalBasePrice += 0.50; if (onions.Checked) totalBasePrice += 0.50; if (potatoes.Checked) totalBasePrice += 0.50; // 计算总价:基础价总和 × 数量 decimal quantity = numericUpDown1.Value; double totalPrice = totalBasePrice * (double)quantity; // 格式化显示到txtTotal(货币格式) txtTotal.Text = totalPrice.ToString("C"); // 传递总价到价格展示窗口 frmShowPrice showprice = new frmShowPrice(); showprice.SubTotal = totalPrice; showprice.ShowDialog(); // 重置表单控件 tomatoes.Checked = false; peppers.Checked = false; onions.Checked = false; potatoes.Checked = false; rbOneScoop.Checked = true; txtTotal.Text = string.Empty; numericUpDown1.Value = numericUpDown1.Minimum; } } private void btnExit_Click(object sender, EventArgs e) { Application.Exit(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void numericUpDown1_ValueChanged(object sender, EventArgs e) { } } }
关键修改说明
- 将
else if改为独立if,支持多选复选框并累加对应价格 - 新增数量有效性验证,避免无效输入
- 计算总价后将结果赋值给
txtTotal.Text,并使用货币格式格式化显示 - 修正验证逻辑,确保检查的是实际需要用户选择的食材复选框
- 重置表单时同步清空总价输入框与数量控件
内容的提问来源于stack exchange,提问作者ZarkProductions
相关产品推荐
相关产品推荐

