Click here to Skip to main content
15,748,748 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
this code works well when i put numbe like 20
but when i need to put data from textbox1.text he make me error, it is smothing in syntax not correct

Cmd.CommandText = "select * from table1 where field1= 20 /pre>

<pre>Cmd.CommandText = "select * from table1 where field1= '" & TextBox1.Text & "'" 

What I have tried:

Cmd.CommandText = "select * from table1 where field1= '" & TextBox1.Text & "'"
Updated 9-Jun-20 3:09am

You don't need the single quotes as you are searching for a numeric value, so that would be:
Cmd.CommandText = "select * from table1 where field1= " & TextBox1.Text 

But a word of warning: it is dangerous doing it this way due to the risk of "SQL injection", it's better to use parameterized queries if your code is used by others.
Read about it here:
How do I parameterized the queries of VB.NET code[^]
And here: Using C# to connect to and query from a SQL database | Sander Rossel[^]
Share this answer
Maciej Los 28-May-20 4:08am    
katkot_rewsh 28-May-20 6:28am    
it works like that
select * from Table1 where Filed1= '" & TextBox1. Text & "'
many thanks
Richard Deeming 28-May-20 15:54pm    
Hope you're ready to pay a massive fine when that SQL Injection[^] vulnerability is used to hack your database! A similar vulnerability cost TalkTalk £400,000 back in 2016, so you'll need pretty deep pockets.
select * from Table1 where Filed1= '" & TextBox1. Text & "'"
Share this answer
phil.o 28-May-20 8:54am    
This is the same as what you have tried and which was not correct.
The only decent way is to use a parameterized query:
using (SqlCommand Cmd = ...)
   Cmd.CommandText = "SELECT * FROM Table1 WHERE Field1 = @value";
   Cmd.Parameters.Add("@value", SqlDbType.NVarChar).Value = TextBox1.Text;
   // Then execute the command.
Cmd.CommandText = "select * from Masterbatch where MBColor = "& Val(ComboBox9.SelectedItem) &""
Share this answer
Richard Deeming 9-Jun-20 10:17am    
You really aren't listening, are you?!

Try typing the following in your textbox, and executing your query:
42'; DELETE FROM Masterbatch; --

Now read up on SQL Injection vulnerabilities, and go and fix all of your database code:
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

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