You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#披萨菜单:如何计算DataGridView食材总价并更新至对应控件?

披萨菜单系统:食材总价自动计算&更新实现方案

嘿,我看了你正在开发的披萨菜单系统的需求和现有代码,咱们先理清楚核心目标,再修正代码里的问题,最后给出完整的实现逻辑:

你的核心需求回顾

  • 三个DataGridView分工:展示披萨菜单、显示选中披萨的已选食材、提供可增减的食材选项
  • 自动计算**已选食材列表(第二个DataGridView)的总价,并把最终价格同步回披萨菜单列表(第一个DataGridView)**的对应披萨行

现有代码的问题点

我注意到你贴的代码里有几个需要修正的地方:

  1. 拼写错误:Currentcell应该是CurrentCell,Contain方法名少了个s,应该是Contains
  2. 逻辑偏差:
    • 你用ingredientList.Contain(i)判断索引是否在Ingredient对象列表里,这完全不匹配逻辑,应该判断食材是否被选中或已加入已选列表
    • total++只是统计食材数量,不是累加价格,应该用total += ingre.Price来计算总价
    • SelectedList.Add(i)添加的是索引值,不是Ingredient对象,会导致数据源类型不匹配,第二个DataGridView无法正确显示
  3. 缺失关键步骤:没有把计算好的总价更新到披萨菜单的对应单元格里

修正后的完整实现代码

下面是调整后的代码,我加上了详细注释,适配你的需求:

// 假设你的Ingredient类定义了Price属性(建议用decimal类型处理价格)
// 假设SelectedList是绑定第二个DataGridView的已选食材列表(推荐用BindingList<Ingredient>实现自动刷新)

// 1. 先判断是否选中了披萨,避免空引用
if (MenuGrid.CurrentRow == null)
{
    MessageBox.Show("请先选中一个披萨!");
    return;
}
DataGridViewRow selectedPizzaRow = MenuGrid.CurrentRow;

// 2. 计算已选食材的总价
decimal totalIngredientPrice = 0;
// 直接遍历已选食材列表(第二个DataGridView的数据源)
foreach (Ingredient selectedIngre in SelectedList)
{
    totalIngredientPrice += selectedIngre.Price;
}

// 3. 处理第三个DataGridView的食材增减操作(示例:添加选中的食材)
foreach (DataGridViewRow row in thirdIngredientGrid.SelectedRows)
{
    Ingredient newIngre = (Ingredient)row.DataBoundItem;
    // 避免重复添加
    if (!SelectedList.Contains(newIngre))
    {
        SelectedList.Add(newIngre);
        totalIngredientPrice += newIngre.Price;
    }
}
// 移除食材的逻辑类似,这里省略:找到要移除的食材,从SelectedList删除并减去对应价格

// 4. 刷新第二个DataGridView的显示(如果用BindingList会自动刷新,否则手动重新绑定)
if (ingredientGrid.DataSource is BindingList<Ingredient> bindingIngreList)
{
    bindingIngreList.ResetBindings(false);
}
else
{
    ingredientGrid.DataSource = null;
    ingredientGrid.DataSource = SelectedList;
}

// 5. 将计算好的总价更新到披萨菜单的对应行(假设价格列的列名是"TotalPrice")
selectedPizzaRow.Cells["TotalPrice"].Value = totalIngredientPrice.ToString("C"); // 格式化货币显示

额外优化建议

  • 用BindingList<Ingredient>代替普通List<Ingredient>作为DataGridView的数据源,这样增删食材时UI会自动刷新,不需要手动重新绑定
  • 给第三个DataGridView添加「添加」「移除」按钮,点击按钮时触发上述价格计算逻辑,操作更直观
  • 价格字段一定要用decimal类型,避免float/double的精度丢失问题

内容的提问来源于stack exchange,提问作者Fajer Albloushi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:52:12