0

I am trying to retrieve just CompanyName associated with CustomerID. But nothing is displayed inside the TextBox when the ComboBox item is changed. I don't get any exceptions.

private void Form1_Load(object sender, EventArgs e)
{
    SqlConnection connection = new SqlConnection(cnn);
    SqlCommand cmd = new SqlCommand("select CustomerID FROM Customers", connection);
    connection.Open();
    SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    while (dr.Read()) {
        comboBox1.Items.Add(dr["CustomerID"]);
    }
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    SqlConnection connection = new SqlConnection(cnn);
    string query = "select * from Customers where CustomerID='" + comboBox1.SelectedIndex + "'";
    SqlCommand cmd = new SqlCommand(query, connection);
    connection.Open();
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read()) {
        textBox1.Text = dr["CompanyName"].ToString();
    }
}

2 Answers 2

1

There is problem in your sql query.Chenge comboBox1.SelectedIndex to comboBox1.SelectedItem.Text.ToString(). Correct it as below.

string query = "select * from Customers where CustomerID='" + comboBox1.SelectedItem.Text.ToString() + "'";
Sign up to request clarification or add additional context in comments.

Comments

0

You Can also change the query like...

string query = "select * from Customers where CustomerID='" + comboBox1.SelectedItem.Text + "'";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.