简体   繁体   中英

Delete data in sql table using c# and present it in gridview

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

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM