how to add quantity in an existing record in vb.net using datagridview

Dani AI

Generated

As describes, the objective is to increase the quantity for an existing product row — not just change a visual cell. As pointed out, the important missing detail is whether the DataGridView is bound (DataTable/BindingSource/TableAdapter) or unbound (manually filled). Core rule: find the record by a unique key (ProductID/SKU), update the underlying data source, then persist and refresh the grid.

If the grid is bound to a DataTable/BindingSource, update the DataRow and call your adapter/tableadapter to persist:

' bound DataTable example
Dim productId As Integer = 123
Dim addQty As Integer = 2

Dim matches() As DataRow = dt.Select("ProductID = " & productId)
If matches.Length > 0 Then
    matches(0)("Quantity") = Convert.ToInt32(matches(0)("Quantity")) + addQty
Else
    Dim nr As DataRow = dt.NewRow()
    nr("ProductID") = productId
    nr("ProductName") = "New item"
    nr("Quantity") = addQty
    dt.Rows.Add(nr)
End If

' persist: TableAdapter.Update(dt)  (do not call AcceptChanges before Update)

If the grid is unbound, find the DataGridViewRow and update its cell, then (optionally) run a DB UPDATE to persist:

' unbound DataGridView
For Each r As DataGridViewRow In DataGridView1.Rows
    If Not r.IsNewRow AndAlso Convert.ToInt32(r.Cells("ProductID").Value) = productId Then
        r.Cells("Quantity").Value = Convert.ToInt32(r.Cells("Quantity").Value) + addQty
        Exit For
    End If
Next

To update directly in SQL (parameterized):

Using cn As New SqlConnection(connString)
    Using cmd As New SqlCommand("UPDATE Products SET Quantity = Quantity + @add WHERE ProductID = @id", cn)
        cmd.Parameters.AddWithValue("@add", addQty)
        cmd.Parameters.AddWithValue("@id", productId)
        cn.Open()
        cmd.ExecuteNonQuery()
    End Using
End Using

Troubleshooting notes: always validate/parset input with Integer.TryParse, call BindingSource.EndEdit or DataGridView.EndEdit before saving, handle DBNull, avoid calling AcceptChanges() before DataAdapter.Update, and use parameterized SQL to prevent injection and concurrency issues.

Recommended Answers

All 2 Replies

That's a very general question. Please be more specific and show what you have done so far.

This is my program how can i add the quantity in the same row / on the same product

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.