简体   繁体   中英

Vb.net DataGridView repeating

I have a problem in my DataGridView, please refer to the image below.

Image 1 shows that I've clicked "Add to Cart" on one of my products, the DataGridView shows the product.

Image 1

The problem is when I want to add another product, the list of products in the DataGridView repeats itself instead of adding another different product. Image 2 shows what happens when I clicked "Add to Cart" on a new product.

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

You don't need to cicle through the grid.
(Of course, this may depend on how you calculate the sub total.)

You just need to add a new Row to the grid, using the current values.

This can be a way to do it.

'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})

This is the result:

在此处输入图片说明

You might also present the values in Currency format:

'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")})

This is the result:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM