How to pass textBox.Text to Sql query

  • Thread starter Thread starter Tim Sprout
  • Start date Start date
T

Tim Sprout

I want button1_Click on Form1 to send a query using the textBox1.Text string
as part of the query. I want to populate a dataGridView from an Access
database file. I am trying to build a search box with the textBox1. How do I
pass the textBox1.Text string to the query? The query string below gives me
one blank row:

string strOleDb = "Select * from ProjectTable WHERE (ProjectName LIKE
'textBox1.Text')";


-Tim Sprout
 
Tim Sprout said:
I want button1_Click on Form1 to send a query using the textBox1.Text
string
as part of the query. I want to populate a dataGridView from an Access
database file. I am trying to build a search box with the textBox1. How do
I
pass the textBox1.Text string to the query? The query string below gives
me
one blank row:

string strOleDb = "Select * from ProjectTable WHERE (ProjectName LIKE
'textBox1.Text')";

The easiest -and not recommended- way to do it is to concatenate the text
to the query:

string strOleDb = "Select * from ProjectTable WHERE (ProjectName LIKE '" +
textBox1.Text + "')";

This would work, BUT it has the risk of suffering what is known as a "Sql
Injection attack": If a user enters in the textbox something that looks like
Sql, it would be executed at your server. It also has other problems, for
instance, if the Text were "O'Donell", the code would crash with a syntax
error due to the single quote.

The recommended way to pass the text is to parameterize the Sql Query:

string strOleDb = "Select * from ProjectTable WHERE (ProjectName LIKE ?)";
OleDbCommand cmd = new OleDbCommand(strOleDb, connection);
cmd.Parameters.AddWithValue("FirstParam", textBox1.Text);
 
The recommended way to pass the text is to parameterize the Sql Query:

string strOleDb = "Select * from ProjectTable WHERE (ProjectName LIKE ?)";
OleDbCommand cmd = new OleDbCommand(strOleDb, connection);
cmd.Parameters.AddWithValue("FirstParam", textBox1.Text);


Thank you!

-Tim Sprout
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top