如何对DataGridView指定列按不同分组求和并绑定到另一DataGridView
DataGridView按指定列分组求和的实现方案
你遇到的空单元格报错问题,是因为代码没有提前过滤空值行,空值调用ToString()、Convert.ToInt32()方法时会触发空引用或格式异常,只要提前增加无效行过滤逻辑即可正常运行。
你需要的完整实现代码如下:
var sumResult = dataGridView1.Rows.Cast<DataGridViewRow>() // 过滤无效行:排除新行、分组列为空、数量列为空的行 .Where(row => !row.IsNewRow && row.Cells[7].Value != null && row.Cells[1].Value != null) // 按group列分组 .GroupBy(row => row.Cells[7].Value.ToString()) // 对每个分组的quantity列求和 .Select(g => new { group = g.Key, quantity = g.Sum(row => Convert.ToInt32(row.Cells[1].Value)) }) .ToList(); // 绑定结果到目标DataGridView dataGridView6.DataSource = sumResult;
额外优化说明
如果你担心quantity列手动输入可能存在非数字格式的问题,可以额外加格式校验,避免转换报错:
var sumResult = dataGridView1.Rows.Cast<DataGridViewRow>() .Where(row => !row.IsNewRow && row.Cells[7].Value != null && row.Cells[1].Value != null && int.TryParse(row.Cells[1].Value.ToString(), out _)) .GroupBy(row => row.Cells[7].Value.ToString()) .Select(g => new { group = g.Key, quantity = g.Sum(row => Convert.ToInt32(row.Cells[1].Value)) }) .ToList(); dataGridView6.DataSource = sumResult;
运行后目标DataGridView会自动生成对应列,展示你需要的分组求和结果。
内容的提问来源于stack exchange,提问作者Gabriele
相关产品推荐
相关产品推荐

