Reputation: 3
Hi all Iam trying to reduce a stock using this code below but Iam getting error, can any one help me pleaseee????`
Public Sub UpdateDecreaseQuantity()
Try
Dim cb As String = "Update Dish SET Quantity = stocksOnHand - '" & DataGridView1.CurrentRow.Cells(2).Value & "' "
con.Open()
cmd = New OleDbCommand(cb, con)
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
con.Close()
End Try
End Sub
Upvotes: 0
Views: 60
Reputation: 3424
Firstly, If DataGridView1.CurrentRow.Cells(2).Value
is 0
length string or Nothing
value you will get this error.
Please check using:
Not String.IsNullOrEmpty(DataGridView1.CurrentRow.Cells(2).Value)
.
Secondly, you have added quotes around the Cell value in the query
'" & DataGridView1.CurrentRow.Cells(2).Value & "' "
Numeric value should not have quotes around.
Thirdly, this query is prone to SQL injection attack. Please try to parameterize the query.
Example:
Dim OtherValue as Integer = 0
Dim cb As String = "Update Dish SET Quantity = stocksOnHand - @OtherValue"
con.Open()
cmd = New OleDbCommand(cb, con)
Int32.TryParse(DataGridView1.CurrentRow.Cells(2).Value, OtherValue)
cmd.Parameters.Add("@OtherValue", SqlDbType.Int).Value = OtherValue
cmd.ExecuteNonQuery()
Upvotes: 1
Reputation: 54417
Just as you use double quotes to signify a String
in VB but do not put them around numbers, so single quotes denote a string in SQL. If you are subtracting two numbers then they must both be numbers, not a one number and a string.
Dim cb As String = "Update Dish SET Quantity = stocksOnHand - " & DataGridView1.CurrentRow.Cells(2).Value.ToString()
Even better would be to learn how to insert values into SQL properly and use parameters.
Upvotes: 0