首页 > 解决方案 > 如何在datagridview中对相同id的值求和?

问题描述

我正在尝试对 datagridview 中相同 id 的值求和并尝试更新 sql 数据库表。怎么做?

在此处输入图像描述

For i As Integer = 0 To DataGridView2.Rows.Count - 1
    If Convert.ToInt32(DataGridView2.Rows(i).Cells(0).Value) = Convert.ToInt32(DataGridView2.Rows(i).Cells(0).Value) Then
        y += Convert.ToInt32(DataGridView2.Rows(i).Cells(3).Value)
    End If
Next

标签: vb.net

解决方案


您可以使用 Dictionary 使用总和值检查和分组 id

Dim totals As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()

For i As Integer = 0 To DataGridView2.Rows.Count - 1
    Dim group As String = Convert.ToInt32(DataGridView2.Rows(i).Cells("id").Value)
    Dim qty As Integer = Convert.ToInt32(DataGridView2.Rows(i).Cells("value").Value)

    If totals.ContainsKey(group) = False Then
        totals.Add(group, qty)
    Else
        totals(group) += qty
    End If

Next

或使用 LINQ 组:

Dim totals = DataGridView2.Rows.Cast(Of DataGridViewRow)().GroupBy(Function(row) row.Cells("id").Value.ToString()).[Select](Function(g) New With {Key
    .id= g.Key, Key
    .SumValues = g.Sum(Function(row) Convert.ToInt32(row.Cells("value").Value))
})

推荐阅读