Click here to Skip to main content
15,358,946 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
It is supposed to subtract the Quantity of BagQty but I'm getting this ExecuteNonQuery error

What I have tried:

namespace BagQtyPractice
public partial class Form1 : Form
SqlConnection con = new SqlConnection("Server=DESKTOP- 1281SGB;Database=Practice;User Id=KicuCrafts; Password = admin; ");
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
public Form1()


private void btnAddtoCart_Click(object sender, EventArgs e)
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update BagPracticeQty set BagQty=BagQty-" + txtQTY.Text;
Updated 1-Jul-18 4:04am
sajeetharan 1-Jul-18 9:20am
Can you elloborate more on the error? what is the error
F-ES Sitecore 2-Jul-18 6:38am
Examine cmd.CommandText in the debugger to see exactly what SQL you are executing also look at the full exception message for more info. It can be handy to run the same code in SQL Server Management Studio.

Regardless your code has a few issues as it is, namely SQL Injection and also as there is no WHERE clause to limit the update to the item in question, your code is going to amend the quantity of every item in BagPracticeQty.

1 solution

Don't do it like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
A perfectly valid "delete the table" command
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

Once you have fixed that throughout you app - and miss one instance and you are at risk - you will probably find that your problem has disappeared.

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