Click here to Skip to main content
15,881,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a code to populate a textbox depending on the ddl value. Why is my code not working? What did I do wrong?

C#
protected void DropDownListLongName_SelectedIndexChanged(object sender, EventArgs e)
        {
            SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["HotConnectionString"].ConnectionString);
            con2.Open();

            SqlCommand scmd = new SqlCommand("Select User_ID, LongName from Table99 where LongName = '" + DropDownListLongName + "'", con2);

            SqlDataReader dr = scmd.ExecuteReader();

            if (dr.Read())

            {
                TextBoxUser_ID.Text = dr["User_ID"].ToString();
            }

            dr.Close();
            con2.Close();
        }
    }
}
Posted
Comments
Richard Deeming 19-May-15 10:21am    
Your code is vulnerable to SQL Injection[^].

NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

1 solution

Start by fixing the SQL Injection[^] vulnerability in your code.

That will then tell you that you're trying to pass the DropDownList control to the query, instead of passing its selected value.

Also, you should wrap all objects that implement IDisposable in a using block.

And to retrieve a single value from the query, there's no need for a DataReader - just call ExecuteScalar.
C#
protected void DropDownListLongName_SelectedIndexChanged(object sender, EventArgs e)
{
    using (SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["HotConnectionString"].ConnectionString))
    using (SqlCommand scmd = new SqlCommand("Select User_ID from Table99 where LongName = @LongName", con2))
    {
        scmd.Parameters.AddWithValue("@LongName", DropDownListLongName.SelectedValue);

        con2.Open();
        TextBoxUser_ID.Text = Convert.ToString(smcd.ExecuteScalar());
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900