Reputation: 173
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();
}
}
Upvotes: 0
Views: 702
Reputation: 2080
You Can also change the query like...
string query = "select * from Customers where CustomerID='" + comboBox1.SelectedItem.Text + "'";
Upvotes: 0
Reputation: 2788
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() + "'";
Upvotes: 1