Click here to Skip to main content
15,885,949 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi I have wrote this small piece of code below to delete a record from a database:

private void button2_Click(object sender, RoutedEventArgs e)
      {
          conn.Open();
          SqlCommand sc = new SqlCommand("DELETE FROM dbo.Food_Items WHERE Food_Name = "+textBox2.Text+"", conn);

          sc.ExecuteNonQuery();
          conn.Close();
      }



The query works perfectly fine if I replace the textBox2 section of the query and replace it with a word. But when I put in a text box and press remover it throws this exception:

Invalid column name 'Beans'.

Beans being the word I have typed into the textBox. I can not for the life of me think why this won't work. Im sure it's something simple that I've typed but I can't see it!

Any help will be appreciated cheers :)
Posted
Updated 6-Jun-11 5:27am
v2

1 solution

You have to escape it, you are missing ' .

From
C#
SqlCommand sc = new SqlCommand("DELETE FROM dbo.Food_Items WHERE Food_Name = "+textBox2.Text+"", conn);

To
C#
SqlCommand sc = new SqlCommand("DELETE FROM dbo.Food_Items WHERE Food_Name = '"+textBox2.Text+"'", conn);


Or even better use SqlParameter[^]
 
Share this answer
 
v2
Comments
DanHodgson88 6-Jun-11 12:12pm    
Cheers Kim appreciated again :)
Kim Togo 6-Jun-11 12:29pm    
You are welcome :-)
Abhinav S 6-Jun-11 14:19pm    
Precise answer. My 5.
Kim Togo 7-Jun-11 2:35am    
Thanks Abhinav
parmar_punit 7-Jun-11 8:05am    
nice answer my 5

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