jamesmc1535
jamesmc1535

Reputation: 25

How can I delete a single entry from a table

I have a listbox with usernames, and a remove button I want the selected a user (with all entered data associated with that user) to be deleted when the remove button is clicked.

My code

SqlConnection con = new SqlConnection("Data Source=JAMES-PC\\SQLEXPRESS;Initial Catalog=staff;Integrated Security=True");
con.Open();

string sql = @"DELETE FROM staff1;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();

this code deletes the whole table.

How can I just delete the selected user?

Upvotes: 2

Views: 183

Answers (3)

Zippy
Zippy

Reputation: 1824

When you execute a delete query, in order to delete only 1 row from the table you need to add a WHERE clause.

Based on the comments the workflow should be something like: you click on a delete button, you send the name of the staff you want to delete to the command, which looks like:

 string sql = @"DELETE FROM staff1 where Name=@Name;";

 SqlCommand cmd = new SqlCommand(sql, con);
 cmd.Parameters.AddWithValue("@Name","NameReceivedFromList");

 cmd.ExecuteNonQuery();
 con.Close();

Upvotes: 1

CharithJ
CharithJ

Reputation: 47540

You need a WHERE clause to select the required record. You have to get the username of the selected user to be deleted and pass it to @UserName parameter.

 var userName = (listBox.SelectedItem as DataRowView)["UserName"].ToString();
 string sql = @"DELETE FROM staff1 WHERE Username = @UserName;";

 SqlCommand cmd = new SqlCommand(sql, con);
 cmd.Parameters.AddWithValue("@UserName",useName);

 cmd.ExecuteNonQuery();
 con.Close();

See this thread on how to use parameters in the SQL.

Upvotes: 2

Donald Jansen
Donald Jansen

Reputation: 1985

When you are deleting you should remember to add a Where clause, it is actually very powerfull here is some examples that will get you started

The following query will delete only one element

DELETE FROM Table WHERE Table.PrimaryField = Value

The following query will delete all items that matches

DELETE FROM Table WHERE Table.Field = Value

You can also have a join in your delete statement for more complex delete queries

DELETE A FROM Table A 
INNER JOIN TableB B ON A.Key = B.Key
WHERE B.PrimaryField = Value

Upvotes: 0

Related Questions