Reputation: 556
I have the following method:
Connection c =new Connection();
SqlCommand cmd = new SqlCommand();
String empID = toolStripTextBox1.Text;
cmd.CommandText = "DELETE FROM tblEmployee WHERE employeeNumber='empID'";
cmd.Connection = c.con;
c.con.Open();
dataGridView1.CurrentCell = null;
int numberDeleted = cmd.ExecuteNonQuery();
MessageBox.Show(numberDeleted.ToString() + " employees were deleted.<br>");
c.con.Close();
I'm trying to delete a record in the table and update gridview to show the remaining records in the table. the code doesn't delete any record
Upvotes: 0
Views: 3308
Reputation: 643
The problem is that probably no empID with the value 'empID' exists..
You didn't put the value of the empID in the command, but added an exact string of 'empID', which cannot be found in your table. Put the empID value as a parameter like Icarus advised.
Upvotes: -1
Reputation: 63970
This:
DELETE FROM tblEmployee WHERE employeeNumber='empID'
Should be converted to use a parametrized query in the following way:
cmd.CommandText="DELETE FROM tblEmployee WHERE employeeNumber=@id";
The reason is that your previous statement was simply concatenating the delete from ...
part with the string 'empid'
which I assume is not what you want. You are after something like this:
delete from ... where employeeNumber={some_number}
where some_number
is a parameter
In order to pass a parameter to your SQL Statement you do this:
cmd.Parameters.AddWithValue("@id",empID);//I assume empID is a variable containing an ID
cmd.ExecuteNonQuery();
If you want the change immediately reflected on your grid, you need to select the data again and rebind your grid.
Upvotes: 4