如何基于DataGridView相同ID的求和值更新ListBox?
问题分析与修复代码
原代码存在几个关键问题导致功能失效:
- 字典键类型不匹配:声明了
Dictionary(Of String, List(Of Decimal)),但实际用整数类型ID作为键,后续判断ListBox项时直接用ID字符串匹配格式化后的完整项,完全不匹配。 - 循环逻辑混乱:在DataGridView行循环内嵌套遍历字典所有键,还通过
Do While修改循环变量i,导致行遍历异常,出现重复或跳过数据的情况。 - ListBox项删除逻辑错误:遍历Items集合时直接删除元素会引发集合修改异常,且判断条件错误(ListBox项是格式化后的完整字符串,不是单纯的ID)。
修复方案1:全量刷新(重新计算所有ID总和并更新ListBox)
适合每次需要从DataGridView重新统计所有数据的场景:
' 先统计所有ID对应的share总和 Dim idSumDict As New Dictionary(Of Integer, Decimal)() For Each row As DataGridViewRow In DataGridView2.Rows ' 跳过空行 If row.IsNewRow Then Continue For Dim laborerId As Integer = Convert.ToInt32(row.Cells(0).Value) Dim share As Decimal = Convert.ToDecimal(row.Cells(3).Value) If idSumDict.ContainsKey(laborerId) Then idSumDict(laborerId) += share Else idSumDict.Add(laborerId, share) End If Next ' 清空ListBox并重新添加统计结果 ListBox1.Items.Clear() Dim prebal As Integer = Convert.ToInt32(Label6.Text) Dim postbal As Integer = 0 For Each kvp In idSumDict ' 用指定格式字符串ces拼接内容 ListBox1.Items.Add(String.Format(ces, kvp.Key, prebal, kvp.Value, postbal)) Next
修复方案2:增量更新(仅更新新增/修改的ID)
适合DataGridView新增行时,单独更新对应ID的ListBox项:
' 获取新增行数据(跳过最后一行默认空行) Dim targetRow As DataGridViewRow = DataGridView2.Rows(DataGridView2.Rows.Count - 2) Dim laborerId As Integer = Convert.ToInt32(targetRow.Cells(0).Value) Dim prebal As Integer = Convert.ToInt32(Label6.Text) Dim postbal As Integer = 0 ' 重新计算该ID的总share Dim totalShare As Decimal = 0 For Each row As DataGridViewRow In DataGridView2.Rows If row.IsNewRow Then Continue For If Convert.ToInt32(row.Cells(0).Value) = laborerId Then totalShare += Convert.ToDecimal(row.Cells(3).Value) End If Next ' 删除ListBox中该ID对应的旧项 Dim itemToRemove As Object = Nothing For Each item In ListBox1.Items ' 假设格式字符串中ID是第一个元素,拆分后匹配 If item.ToString().Split(","c)(0).Trim() = laborerId.ToString() Then itemToRemove = item Exit For End If Next If itemToRemove IsNot Nothing Then ListBox1.Items.Remove(itemToRemove) End If ' 添加更新后的项 ListBox1.Items.Add(String.Format(ces, laborerId, prebal, totalShare, postbal))
内容的提问来源于stack exchange,提问作者pankaj babbar
相关产品推荐
相关产品推荐

