Question

I am new in .net. I have the following code and I know it is incorrect:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
        {
            SqlConnection conn = new SqlConnection("Connection");
            SqlCommand cmd = new SqlCommand("SELECT * FROM Users ORDER BY FirstName", conn);

            conn.Open();
            SqlDataReader rd = cmd.ExecuteReader();
            ddlUsers.DataValueField = "ID";
            ddlUsers.DataTextField = "FirstName";
            ddlUsers.DataSource = rd;
            ddlUsers.DataBind();
            rd.Close();

            SqlCommand cmd1 = new SqlCommand("SELECT [LastName], [Email], [Phone] FROM [Users] WHERE ([FirstName] = @FirstName)", conn);
            cmd1.Parameters.AddWithValue("@FirstName", ddlUsers.SelectedItem.ToString());
            SqlDataReader rd1 = cmd1.ExecuteReader();
            while (rd1.Read())
            {
                lblPhoneShow.Text = rd1["Phone"].ToString();
                lblEmailShow.Text = rd1["Email"].ToString();
                lblLNShow.Text = rd1["LastName"].ToString();
            }
            conn.Close();
        }

        } 

Binding data to dropdown works great, but when I choose certain name, labels show nothing. Can anyone explain me what I am doing wrong? Thanks!

Was it helpful?

Solution

You don't appear to be executing the query.

Try this:

SqlCommand cmd1 = new SqlCommand("Select (Phone, LastName, Email) from users where FirstName = @FirstName", conn);
cmd.Parameters.AddWithValue("@FirstName", ddlUsers.SelectedValue.ToString());
rd = cmd.ExecuteReader()

UPDATE

The dropdown lists's value is the ID. You're comparing the FirstName in the database to this value. A firstname will never match an ID.

  • If you want to search by the ID, change the SQL.
  • If you want to search by the Name, change the property to SelectedItem (which will be a DataRow). Then drill down to the name.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top