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

VB.NET ListView重复项合并求助:如何更新而非新增重复行?

VB.NET ListView购物车合并重复项实现

修改后的代码实现

' 解析输入数据并转换为数值类型,避免字符串操作错误
Dim addQty As Integer = Integer.Parse(txtquantity.Text)
Dim coffeeName As String = txtname.Text.Trim()
Dim size As String = cmbsize.Text.Trim()
Dim type As String = cmbtype.Text.Trim()
Dim unitPrice As Decimal = Decimal.Parse(txtprice.Text)
Dim addTotalPrice As Decimal = addQty * unitPrice

' 查找是否存在咖啡名、尺寸、类型完全匹配的重复项
Dim existingItem As ListViewItem = Nothing
For Each item As ListViewItem In lvwcart.Items
    If item.SubItems(1).Text.Trim() = coffeeName AndAlso _
       item.SubItems(2).Text.Trim() = size AndAlso _
       item.SubItems(3).Text.Trim() = type Then
        existingItem = item
        Exit For
    End If
Next

If existingItem IsNot Nothing Then
    ' 更新重复项的数量和总价
    Dim currentQty As Integer = Integer.Parse(existingItem.SubItems(0).Text)
    Dim currentTotalPrice As Decimal = Decimal.Parse(existingItem.SubItems(4).Text)
    
    existingItem.SubItems(0).Text = (currentQty + addQty).ToString()
    existingItem.SubItems(4).Text = (currentTotalPrice + addTotalPrice).ToString()
Else
    ' 无重复项,新增购物车条目
    Dim itm As New ListViewItem(addQty.ToString())
    itm.SubItems.Add(coffeeName)
    itm.SubItems.Add(size)
    itm.SubItems.Add(type)
    itm.SubItems.Add(addTotalPrice.ToString())
    lvwcart.Items.Add(itm)
End If

核心逻辑说明

  1. 输入数据处理:将数量、单价转换为数值类型,对文本字段做Trim()处理,避免空格导致的匹配失败,同时计算本次添加的总价。
  2. 重复项检测:遍历ListView所有条目,对比Coffee(SubItems[1])、Size(SubItems[2])、Type(SubItems[3])三个字段,判定是否为重复项。
  3. 重复项更新:找到重复项后,取出原有数量和总价,累加新输入的数量和总价,更新对应列的文本。
  4. 新条目添加:未找到重复项时,按原有逻辑新增条目,确保总价为数量×单价,保证数据一致性。

可选优化建议

  • 加入异常处理:使用Integer.TryParse和Decimal.TryParse替代直接Parse,避免输入非数字内容导致程序崩溃。
  • 若Price列存储的是单份价格而非总价,只需更新数量列,保留Price列数值不变即可,调整总价计算逻辑即可适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 09:57:07