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

C# 检查DataGridView指定行是否存在 存在更新数量否则新增行

代码修改实现

你可以直接使用下方修改后的代码,核心新增了条码匹配校验、已存在行qty累加的逻辑,同时修正了原代码中数据库连接操作顺序的问题:

// 先判断并打开数据库连接,避免重复打开/未打开先关闭触发异常
if (com.State != System.Data.ConnectionState.Open)
{
    com.Open();
}

SqlCommand cmd = new SqlCommand("calldata", com);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@barcode", Convert.ToInt64(txtbarcode.Text));
txtbarcode.Text = "";

dtgproduct.DataSource = dataTable.DefaultView;
// 原代码声明的SqlDataAdapter未实际使用,不需要可直接删除
// SqlDataAdapter da = new SqlDataAdapter(cmd);

SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
    // 读取当前返回数据的条码(第0列值)
    string currentBarcode = reader[0].ToString();
    // 转义单引号避免查询异常,按第0列匹配现有数据行
    string filter = $"[{dataTable.Columns[0].ColumnName}] = '{currentBarcode.Replace("'", "''")}'";
    DataRow[] matchedRows = dataTable.Select(filter);

    if (matchedRows.Length > 0)
    {
        // 已存在匹配行,qty列数值+1,请将下方索引5替换为你实际qty列的索引
        matchedRows[0][5] = Convert.ToInt32(matchedRows[0][5]) + 1;
    }
    else
    {
        // 无匹配行,新增数据行
        DataRow dr = dataTable.NewRow();
        dr[0] = reader[0];
        dr[1] = reader[1];
        dr[2] = reader[2];
        dr[3] = reader[3];
        dr[4] = reader[4];
        dr[5] = reader[5];
        dataTable.Rows.Add(dr);
    }
}

// 资源释放
reader.Close();
com.Close();

注意说明

  • 代码中默认qty字段是第6列(索引值为5),请根据你实际业务中qty列的位置修改对应索引值
  • 新增了条码内容单引号转义逻辑,避免条码包含单引号时查询报错
  • 调整了原代码的连接操作顺序,避免未打开连接就执行Close触发运行时异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:36:04