Question

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();
    }
}
Was it helpful?

Solution

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() + "'";

OTHER TIPS

You Can also change the query like...

string query = "select * from Customers where CustomerID='" + comboBox1.SelectedItem.Text + "'";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top