sarika sarikaa

sarika sarikaa

  • NA
  • 60
  • 8.4k

Parameterized query for like clause to avoid sql injection

Apr 26 2018 6:07 AM
private void Form2_Load(object sender, EventArgs e)
{
con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\DATABASE\data.sql.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
adpt = new SqlDataAdapter(" select * from Tab ", con);
dt = new DataTable("Tab");
adpt.Fill(dt);
DataGridView.DataSource = dt;
DataGridView.Columns["Drawing"].DefaultCellStyle.ForeColor = Color.Blue;
DataGridView.Columns["Drawing"].DefaultCellStyle.Font = new Font(DataGridView.DefaultCellStyle.Font, FontStyle.Underline);
gridview_data();
}
private void TxtSearch_TextChanged(object sender, EventArgs e)
{
try
{
// = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\DATABASE\data.sql.mdf;Integrated Security=True;Connect Timeout=30");
//con.Open();
con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\DATABASE\data.sql.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
adpt = new SqlDataAdapter(" select * from Tab Where [Part_No] like '%" + TxtSearch.Text + "%' AND [Company_Name] like '%" + TextBox1.Text + "%'", con);
//adpt = new SqlDataAdapter(" select * from Tab Where [Part_No] like '%" + TxtSearch.Text + "%' AND [Company_Name] like '%" + TextBox1.Text + "%'", con);
// SqlCommand sda = new SqlCommand(" select * from Tab Where [Part_No] like '%@Part_No%' and [Company_Name] like '%@Company_Name%'", con);
//sda.Parameters.Clear();
// sda.Parameters.AddWithValue("Part_No", TxtSearch.Text );
 //sda.Parameters.AddWithValue("Company_Name", TextBox1.Text );
dt = new DataTable("Tab");
adpt.Fill(dt);
DataGridView.DataSource = dt;
con.Close();
if (dt.Rows.Count <= 0)
{
DataRow row1 = dt.NewRow();
row1[0] = "No Record Found";
dt.Rows.Add(row1);
DataGridView.Rows[0].DefaultCellStyle.BackColor = Color.Yellow;
DataGridView.DefaultCellStyle.Font = new Font("Regular", 12, FontStyle.Regular);
}
else
{
DataGridView.Rows[0].DefaultCellStyle.BackColor = Color.Red;
DataGridView.DefaultCellStyle.Font = new Font("Regular", 12, FontStyle.Regular);
}
if (TextBox1.Text == "" && TxtSearch.Text == "")
{
con.Open();
adpt = new SqlDataAdapter(" select * from Tab ", con);
dt = new DataTable("Tab");
adpt.Fill(dt);
DataGridView.DataSource = dt;
con.Close();
}
}
 
 please give me a query in parameterized form to avod sql injection attack. 

Answers (1)