Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
VB.NET
Dim intQty As Integer

          For Each row As DataGridViewRow In Me.DataGridView1.Rows
              Dim intProductID As Integer
              Dim strSQL As String

              If row.Cells(0).Value > 0 Then
                  intProductID = row.Cells(0).Value
                  intQty = row.Cells(3).Value

                  strSQL = "UPDATE Items SET Quantity = Quantity - " & intQty & " WHERE Barcode = " & intProductID

                  Dim cmd_a As OleDbCommand = New OleDbCommand(strSQL, cnn)

                  cmd_a.ExecuteNonQuery()
              End If
          Next row


What I have tried:

I'm getting an error, Number of query values and destination fields are not the same.
What code am i going to use?
Posted
Updated 21-Oct-16 10:03am

First of all,
(it's very very important) you are inviting hackers to have their hands on with your code using SQL Injection. You ignore this and they'll hit the right place.

-- I hope, you are sharing the correct piece of code
-- Make sure that your Barcode is an int field in database. If not enclose the value with pair of single quotes.
-- Enclose the subtraction with a pair of brackets like (Quantity - " & intQty & ")

If you still get the error, please let me know.
Hope, it helps :)
 
Share this answer
 
Comments
CaptainChizni 21-Oct-16 15:57pm    
It really works, Thank You :)
Suvendu Shekhar Giri 21-Oct-16 16:52pm    
Glad that it helped :)
Follow the steps from MSDN documentation: Number of query values and destination fields are not the same. (Error 3346) [Access 2007 Developer Reference][^] to resolve your issue.

Suvendu Shekhar Giri[^] warned you about sql injection. So, you have to use parameterized query instead of concatenated string, such as:
VB.NET
strSQL = "UPDATE Items SET Quantity = Quantity - @qty WHERE Barcode = @barcode;"
cmd.Parameters.AddWithValue("@qty", intQty)
cmd.Parameters.AddWithValue("@barcode", intProductID)


Do NOT forget to add [;] at the end of command line! MS Access really likes it ;)

For further details, please see this:
UPDATE Statement (Microsoft Access SQL) [Access 2007 Developer Reference][^]
Insert, Update, and Delete Records From a Table Using Access SQL[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900