0

我正在尝试仅检索与 CustomerID 关联的 CompanyName。但是当 ComboBox 项发生更改时,TextBox 内不会显示任何内容。我没有任何例外。

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();
    }
}
4

2 回答 2

1

您的 sql 查询中存在问题。将 comboBox1.SelectedIndex 更改为 comboBox1.SelectedItem.Text.ToString()。更正如下。

string query = "select * from Customers where CustomerID='" + comboBox1.SelectedItem.Text.ToString() + "'";
于 2013-08-09T15:59:50.003 回答
0

您还可以更改查询,例如...

string query = "select * from Customers where CustomerID='" + comboBox1.SelectedItem.Text + "'";
于 2013-08-10T16:26:15.340 回答