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

如何在DevExpress Grid Control中实现商品重复添加时仅增数量不新增行

DevExpress GridControl 重复添加商品时递增数量而非新增行的问题修复

问题分析

你的代码核心逻辑方向正确,但存在几个细节问题导致重复添加时无法正确匹配已有商品:

  • 找到匹配行后未终止循环(虽不影响结果但浪费性能)
  • 更新数量时将数值转为字符串赋值,可能导致后续数据类型判断异常
  • 循环条件可以简化,同时需确保ID匹配的数据源取值准确

修正后的代码

bool isProductFound = false;
// 提前提取并转换当前要添加的商品ID,避免重复转换操作
int targetProductId = Convert.ToInt32(tblItems.Rows[0][0]);

// 遍历现有行查找匹配商品
for (int i = 0; i < gridView1.RowCount; i++)
{
    int existingProductId = Convert.ToInt32(gridView1.GetRowCellValue(i, "id"));
    if (existingProductId == targetProductId)
    {
        // 读取当前数量并递增,保持数值类型赋值
        int currentQty = Convert.ToInt32(gridView1.GetRowCellValue(i, "qty"));
        gridView1.SetRowCellValue(i, "qty", currentQty + 1);
        isProductFound = true;
        break; // 找到匹配项后立即终止循环,提升效率
    }
}

// 未找到匹配商品则新增行
if (!isProductFound)
{
    gridView1.AddNewRow();
    int newRowHandle = GridControl.NewItemRowHandle;
    
    gridView1.SetRowCellValue(newRowHandle, "id", Product_ID);
    gridView1.SetRowCellValue(newRowHandle, "item", Product_Name);
    gridView1.SetRowCellValue(newRowHandle, "size", Product_Unit);
    gridView1.SetRowCellValue(newRowHandle, "qty", Product_Qty);

    tblUnit = db.readData($"select * from Products where Pro_ID={categoryID}", "");
    decimal realPrice = 0;
    try
    {
        realPrice = Convert.ToDecimal(tblUnit.Rows[0][7]);
    }
    catch (Exception) { }
    gridView1.SetRowCellValue(newRowHandle, "price", realPrice);

    decimal total = Convert.ToDecimal(Product_Qty) * realPrice;
    gridView1.SetRowCellValue(newRowHandle, "total", total);
    
    gridView1.SetRowCellValue(newRowHandle, "Product_Group_ID", Product_Group_ID);
    gridView1.SetRowCellValue(newRowHandle, "print", Product_PRINTNAME);
    gridView1.SetRowCellValue(newRowHandle, "protax", Product_tax);
    gridView1.SetRowCellValue(newRowHandle, "Note", " ");
}

额外优化建议

  • 建议将GridControl绑定为强类型集合(如List<Product>),直接操作数据源而非单元格,逻辑更清晰且不易出错
  • 避免字符串拼接SQL语句,改用参数化查询防止SQL注入风险
  • 对tblItems.Rows[0][0]的取值增加空值与索引判断,防止空引用或索引越界异常

内容的提问来源于stack exchange,提问作者Technical Quality-TQ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:15:41