Reputation: 3051
I want to find the text in textbox in my database. I wrote the code below. It finds numbers well, but when I want to find strings it gives a runtime error: invalid column name for example aaa
, but aaa exists in column1 in my table.
What do you think about the problem?
cmd = New SqlCommand("select * from tbl where column1=" + TextBox1.Text)
cmd.CommandType = CommandType.Text
cmd.Connection = cnn
dad.SelectCommand = cmd
cmd.ExecuteNonQuery()
dad.Fill(ds)
dgv.DataSource = ds.Tables(0)
Upvotes: 1
Views: 682
Reputation: 3453
Adritt is right, you must enclose the text to find within single quotes and, provided that very text doesn't contains single quotes, all is well - Apart for the risk of SQL attacks.
That being said, you are using an outdated, obsolete way of coding your app against the database.
You should definitively have a deep look at LINQ technology where:
Example:
using ctx as new dataContext1
dim result = from r in ctx.tbl
where r.column1 = textBox1.text
dgv.datasource = result.tolist
end using
Intellisense:
LINQ is not difficult to learn and you'll find tons of examples to help you, here and there on the web.
Last but not least, you can use the LINQ SQL-like syntax to query XML data, CSV files, Excel spreadsheets and even the controls in your form, or the HTML DOM document in ASP.NET!
Upvotes: 1
Reputation: 57783
That's because the sql statement you send is not delimiting the TextBox1.Text
value so you end up with this sql:
select * from tbl where column1 = aaa
and SQL Server treats aaa
as a column name.
Regardless of that, you should be using a SqlParameter
to avoid sql injection attacks:
cmd = New SqlCommand("select * from tbl where column1=@value")
cmd.CommandType = CommandType.Text
cmd.Paramaters.AddWithValue("@value", TextBox1.Text)
VB is not my primary language, so the syntax might be a little off, but you should be able to make it work.
Upvotes: 3