0

I'm trying to display the SQL query result in a label but it's not showing. The user picks a value from the dropdown list and the label should populate the result. a This is my code:

protected void drpEmployeeName_SelectedIndexChanged(object sender, EventArgs e)
{
    String connString = ConfigurationManager.ConnectionStrings["HRPlannerConnectionString1"].ConnectionString;
    SqlConnection conn = new SqlConnection(connString); 
    string result = "SELECT EmployeeName from Employees WHERE EmployeeID= '" + drpEmployeeName.SelectedItem.Value + "'";
    SqlCommand showresult = new SqlCommand(result, conn);
    conn.Open();
    lblEmployee.Text = showresult.ExecuteScalar().ToString();
    conn.Close();
}

Please help!

wazz
  • 4,953
  • 5
  • 20
  • 34

2 Answers2

0

"AutoPostBack" property of your dropdown might not be set or set to "false". Change it to "true". Also user sql command parameters instead of directly plugging in the user selected value into the query. This will prevent SQL injection.

Try the below code

protected void drpEmployeeName_SelectedIndexChanged(object sender, EventArgs e)
        {
            String connString = ConfigurationManager.ConnectionStrings["HRPlannerConnectionString1"].ConnectionString;
            SqlConnection conn = new SqlConnection(connString); 
            string result = "SELECT EmployeeName from Employees WHERE EmployeeID=@empID";

            SqlCommand showresult = new SqlCommand(result, conn);
      showresult.Parameters.AddWithValue("@empID",drpEmployeeName.SelectedItem.Value);
            conn.Open();
            lblEmployee.Text = showresult.ExecuteScalar().ToString();
            conn.Close();
        }
Akshey Bhat
  • 8,227
  • 1
  • 20
  • 20
0

Make sure your function drpEmployeeName_SelectedIndexChanged is executed. You can verify that by putting a debug point inside the function.

If the code is not kicking in, chances are your drop down select list has auto_postback = "false". Change that to true.

Or your IndexChange procedure may be inccorectly wired (wired to a different control?). Simply remove the code and create a new one.

Also make sure your are actually returning a value from the database.

TheTechGuy
  • 16,560
  • 16
  • 115
  • 136