I have created a shopping system with two different interfaces. The admin interface is used to add/update/delete items to the database and the customer interface to purchase products. I have a problem updating the quantity in the admin interface after the user bought the product. The quantity in the admin interface is updated till the value goes negative.
Try
For Each row As DataGridViewRow In formPOS.ProductAddToCartDGV.Rows
dbconnection()
sql = "UPDATE products_database SET Product_Quantity = Product_Quantity - @ProductQuantity WHERE Product_Code = @ProductCode;"
cmd = New MySqlCommand
With cmd
.Connection = conn
.CommandText = sql
.Parameters.Clear()
.Parameters.AddWithValue("@ProductCode", row.Cells(0).Value)
.Parameters.AddWithValue("@ProductQuantity", row.Cells(3).Value)
result = .ExecuteNonQuery()
If result = 0 Then
MsgBox("Error in updating stocks")
Else
MsgBox("Successfully update stocks")
End If
End With
Next
Catch ex As Exception
MsgBox(ex.Message)
Finally
conn.Close()
End Try
Do you want to ensure that the value entered by customer is less than or equal to the remaining total? If so, you can add a condition Product_Quantity >= CAST(@ProductQuantity AS int)
in WHERE
clause.
For i As Integer = 0 To CustomerDGV.Rows.Count - 2
Dim constr As String = "connection string"
Dim sql As String = "UPDATE products_database SET Product_Quantity = Product_Quantity - @ProductQuantity WHERE Product_Code = CAST(@ProductCode AS int) AND Product_Quantity >= CAST(@ProductQuantity AS int)"
Using conn As SqlConnection = New SqlConnection(constr)
conn.Open()
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.Parameters.AddWithValue("@ProductCode", CustomerDGV.Rows(i).Cells(0).Value)
cmd.Parameters.AddWithValue("@ProductQuantity", CustomerDGV.Rows(i).Cells(1).Value)
Dim rows As Integer = cmd.ExecuteNonQuery()
If rows = 0 Then
MessageBox.Show($"Make sure {CustomerDGV.Rows(i).Cells(0).Value} ProductQuantity <= Product_Quantity")
End If
End Using
Next
Note: this is a SQL Server demo.
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.