Vb.net DataGridView重复

时间:2017-12-02 14:11:44

标签: vb.net datagridview

我的DataGridView有问题,请参考下图。

图片1显示我已点击"添加到购物车"在我的一个产品上,DataGridView显示了该产品。

Image 1

问题是,当我想添加另一个产品时,DataGridView中的产品列表会自行重复,而不是添加另一个不同的产品。 图2显示了当我点击"添加到购物车"关于新产品。

Image 2

 Private Sub btn_add_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_add.Click

    grd_cart.RowCount = grd_cart.RowCount + 1

    For i As Integer = 0 To grd_cart.RowCount - 1

        Dim product As String = grd_cart(0, i).Value
        Dim price As String = grd_cart(1, i).Value
        Dim quantity As String = grd_cart(2, i).Value
        Dim subtotal As String = grd_cart(3, i).Value

        grd_cart(0, i).Value = txt_product_id.Text
        grd_cart(1, i).Value = txt_price.Text
        grd_cart(2, i).Value = num_quantity.Value
        grd_cart(3, i).Value = grd_cart(1, 0).Value * grd_cart(2, 0).Value

    Next

End Sub

1 个答案:

答案 0 :(得分:0)

你不需要穿过网格 (当然,这可能取决于你如何计算子总数。)

您只需使用当前值向网格添加新行。

这可以是一种方法。

'Check whether the Price value is a number or not (to be safe)
'If can't be used as a number, return
Dim _Price As Long
If Long.TryParse(txt_price.Text, _Price) = False Then Return

'Calculate the subtotal value based on quantity and unit price
'I know not everyone calculates the sub total this way. In case, just add a comment.
Dim _subtotal As Long = CLng(num_quantity.Value) * _Price

'Add the new Row values
grd_cart.Rows.Add(New String() {txt_product_id.Text,
                                _Price.ToString,
                                num_quantity.Value.ToString,
                                _subtotal.ToString})

结果如下:

enter image description here

您还可以使用货币格式显示值:

'The output can also be formatted using the local Currency format
grd_cart.Rows.Add(New String() {txt_product_id.Text,
                                _Price.ToString("C"),
                                num_quantity.Value.ToString,
                                _subtotal.ToString("C")})

结果如下:

enter image description here