You need to learn about variable scope:
Basic concepts - C# language specification | Microsoft Learn[
^]
You declare two variables called
sql
which only exist within the scope of the
if
blocks. You cannot use either of them outside of those blocks.
You need to declare one variable, outside of those blocks, and use that instead:
string sql;
if (DropDownList1.SelectedItem.Text == "Name")
{
sql = "...";
}
else if (DropDownList1.SelectedItem.Text == "Specialization")
{
sql = "...";
}
However, you have a much bigger problem: your code is vulnerable to
SQL Injection[
^].
NEVER use string concatenation/interpolation to build a SQL query.
ALWAYS use a parameterized query.
string sql;
if (DropDownList1.SelectedItem.Text=="Name")
{
sql = "select doctor_id, name, address, contact_no, email_id, specialization from doctor_add where name Like @SearchText";
}
else if (DropDownList1.SelectedItem.Text == "Specialization")
{
sql = "select doctor_id, name, address, contact_no, email_id, specialization from doctor_add where specialization Like @SearchText";
}
SqlDataAdapter adp = new SqlDataAdapter(sql, con);
adp.SelectCommand.Parameters.AddWithValue("@SearchText", TextBox1.Text + "%");
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
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[
^]