user2015858
user2015858

Reputation: 47

Deleting a row from a table seems to fail

I'm having difficulty getting a row deleted from a SQL database, I don't get any errors and it seems to work fine, but nothing is deleted. When I Run the code it will output "NAME has been deleted"

Thanks for any help.

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\MyDB.mdf;Integrated Security=True";

try
{
    conn.Open();
    SqlCommand Command = conn.CreateCommand();
    Command.CommandText = "DELETE FROM Contacts WHERE [First Name] = '@Name';";
    Command.Parameters.AddWithValue("@Name", DropDownList1.SelectedValue);
    Command.ExecuteNonQuery();
    TextBox1.Text = DropDownList1.SelectedValue + " Has Been Deleted";
}
catch (Exception ex)
{
    TextBox1.Text = "Nope";
}
finally
{
    conn.Close();
} 

Upvotes: 2

Views: 141

Answers (4)

Brian
Brian

Reputation: 5119

A few things detailed below:

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\MyDB.mdf;Integrated Security=True";

try
{
   conn.Open();
   SqlCommand Command = conn.CreateCommand();
   Command.CommandText = "DELETE FROM Contacts WHERE [First Name] = Name;"; // You don't need the '' or the '@' in your parameter name.
   Command.Parameters.AddWithValue("@Name", comboBox1.SelectedValue);
   if (Command.ExecuteNonQuery() > 0)  //  Add a conditional here that checks for > 0 and THEN set your validation text.
      textBox1.Text = comboBox1.SelectedValue + " Has Been Deleted";
}

catch (Exception ex)
{
   textBox1.Text = "Nope";
}

finally
{
   conn.Close();
} 

Upvotes: 1

wgraham
wgraham

Reputation: 1393

You do not need the single quotes with a parameterized query.

Upvotes: 4

SamiHuutoniemi
SamiHuutoniemi

Reputation: 1595

Remove the quotes around the parameter. Also remove the @-sign from the parameter, where you add it to the command.

Command.CommandText = "DELETE FROM Contacts WHERE [First Name] = @Name;";
Command.Parameters.AddWithValue("Name", DropDownList1.SelectedValue);

Upvotes: 4

Chris Kooken
Chris Kooken

Reputation: 33930

Your criteria is most likely not being met. (Quotes around parameter) So no records are being deleted.

Command.ExecuteNonQuery();

returns an int of the record count. So you can check this against zero to make sure it was deleted.

Upvotes: 2

Related Questions