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

计费软件中DataGridView同条码行合并(含备注判断)的技术问询

计费软件DataGridView行合并实现方案

需求说明

  • 点击按钮时,合并DataGridView中条码相同的行
  • 包含备注的行不参与合并

实现代码(C#)

private void button3_Click(object sender, EventArgs e)
{
    int GROW = dataGridView1.RowCount;
    for(int i=0; i<GROW; i++)
    {
        DataGridViewRow row= dataGridView1.Rows[i];
        string A = row.Cells[0].Value.ToString();
        for(int j = 0; j< GROW; j++)
        {
            if(j == i)
            {
                continue; // 跳过当前行自身
            }
            else
            {
                DataGridViewRow rowb= dataGridView1.Rows[j];
                string B = rowb.Cells[0].Value.ToString();
                if (A == B)
                {   
                    string rema = row.Cells[8].Value.ToString();
                    string remb = rowb.Cells[8].Value.ToString();
                    if(rema == "" && remb == "")
                    {
                        // 累加数量(列2)与金额(列7)
                        string qa = row.Cells[2].Value.ToString();
                        string qb = rowb.Cells[2].Value.ToString();
                        decimal qad = Convert.ToDecimal(qa);
                        decimal qbd = Convert.ToDecimal(qb);
                        decimal tqd = qad + qbd;
                        
                        string ra = row.Cells[7].Value.ToString();
                        string rb = rowb.Cells[7].Value.ToString();
                        decimal rad = Convert.ToDecimal(ra);
                        decimal rbd = Convert.ToDecimal(rb);
                        decimal trd = rad + rbd;
                        
                        row.Cells[7].Value = trd;
                        row.Cells[2].Value= tqd;
                        
                        dataGridView1.Rows.RemoveAt(j);
                        GROW--;
                    }
                }
            }
        }
    }
}

代码逻辑说明

  • 外层循环遍历每一行,内层循环对比其余行的条码(对应列索引0)
  • 仅当两行均无备注(列索引8为空)且条码一致时,执行合并:将被合并行的数量、金额累加到当前行,随后删除被合并行
  • 删除行后同步更新总行数GROW,避免循环过程中出现索引越界问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:41:43