I am working on a news based site. And the site has a search bar for the Newstitle and I don't want to let SQL injections happen on it.
What I am doing is to get the text from the textbox and then use a query to fetch the matching results. This is what happens when a user clicks the search button:
protected void button_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
try
{
SqlCommand comm = new SqlCommand("SELECT * FROM news
Where newstilte LIKE '%" + searchbox.text + "%'", conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
myRepeater.DataSource = reader;
myRepeater.DataBind();
reader.Close();
}
catch (Exception exception)
{
Response.Write(exception.ToString());
}
finally
{
conn.Close();
}
}
As you can see I then use a repeater to show the results. I am wondering how can I prevent SQL injection in the part where people write in the textbox.