如果DataGridView项已存在,请添加数量

时间:2017-02-02 12:02:40

标签: vb.net datagridview

我使用DataGridView创建了一个购物车,在添加到购物车按钮上我有以下代码:

Dim a As Integer
Dim total As Integer
Dim b As Integer
a = TextBox2.Text
b = NumericUpDown56.Value
total = a * b
ShoppingCart.DataGridView1.Rows.Add(Me.Label11.Text, Me.TextBox2.Text, Me.NumericUpDown56.Value, total)
Me.Hide()
ShoppingCart.Show()

如果我重新添加相同项目,如何添加数量?

1 个答案:

答案 0 :(得分:0)

如果不完全知道文本框和updowncounter会做什么,有点难以回答这个问题...但假设您只希望更新计数器更改......

您可以遍历数据并在第一列中搜索相同的文本

    Dim a As Integer
    Dim total As Integer
    Dim b As Integer
    a = TextBox2.Text
    b = NumericUpDown56.Value
    total = a * b
    Dim Updated As Boolean
    For Each row As DataGridViewRow In ShoppingCart.DataGridView1.Rows
        If CType(row.Cells(0).Value, String) = Me.Label11.text Then
            row.Cells(2).Value = CType(row.Cells(0).Value, Integer) + b
            row.Cells(3).Value = CType(row.Cells(3).Value, Integer) + total
            Updated = True
            Exit For
        End If
    Next
    If Not Updated Then ShoppingCart.DataGridView1.Rows.Add(Me.Label11.Text, Me.TextBox2.Text, Me.NumericUpDown56.Value, total)
    Me.Hide()
    ShoppingCart.Show()

虽然我亲自将datagridview绑定到List(T)(t =保留属性的类)并搜索/修改它,然后重新绑定列表。

这些方面的东西......

Private Class cls_Cart_Item
    Public Property Item_Name As String
    Public Property Whatever_TExtbox2_IS_SUpposed_to_be As Integer
    Public Quantity As Integer
    Public Sub New(wName As String, wWhatever_TExtbox2_IS_SUpposed_to_be As Integer, wQuantity As Integer)
        Item_Name = wName
        Whatever_TExtbox2_IS_SUpposed_to_be = wWhatever_TExtbox2_IS_SUpposed_to_be
        Quantity = wQuantity
    End Sub
    Public ReadOnly Property Total As Integer
        Get
            Return Whatever_TExtbox2_IS_SUpposed_to_be * Quantity
        End Get
    End Property
End Class
Private Cart As New List(Of cls_Cart_Item)

Private Sub Add_Or_Update()
    ShoppingCart.datagridview1.datasource = Nothing
    Dim a As Integer
    Dim total As Integer
    Dim b As Integer
    a = TextBox2.Text
    b = NumericUpDown56.Value

    Dim Item As New cls_Cart_Item = Cart.Find(Function(x) x.Item_Name = Me.Label11.Text)
    If Item Is Nothing Then
        Cart.Add(New cls_Cart_Item(Me.Label11.Text, a, b))
    Else
        Item.Quantity += b
    End If
    Me.Hide()

    ShoppingCart.datagridview1.datasource = Cart

End Sub

虽然很难从你的问题中判断出这段代码来自daraviewgrid。