0

我正在尝试用我的数据库中的值填充我的文本框,因此当用户从组合框中选择老师的姓名时,文本框将填充他们的联系方式。这是我到目前为止的代码。没有错误,但是当我从组合框中选择一个值时,文本框仍然是空白的。

    private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        MySqlConnection cs = new MySqlConnection(connectionSQL);
        cs.Open();

        DataSet ds = new DataSet();

        MySqlDataAdapter da = new MySqlDataAdapter("Select * from Teacher WHERE name='" + comboBox1.Text + "'", cs);

        MySqlCommandBuilder cmd = new MySqlCommandBuilder(da);

        da.Fill(ds);


        if (comboBox1.SelectedIndex > 0)
        {


            NameBox.Text = ds.Tables[0].Rows[0]["name"].ToString();
            AddressBox.Text = ds.Tables[0].Rows[0]["address"].ToString();

        }

任何帮助或建议将不胜感激

4

3 回答 3

0

我必须相信,根据您的代码,问题就在这里:

if (comboBox1.SelectedIndex > 0)

如果列表中只有一个项目用户选择了第一个项目,则查询将运行,但不会填充文本框。

于 2013-04-03T17:07:33.477 回答
0

您在验证所选索引之前查询数据库,并且您应该检查大于 -1 而不是 0 的所选索引。

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (comboBox1.SelectIndex < 0) 
    {
        // Don't want to suffer database hit if nothing is selected
        // Simply clear text boxes and return
        NameBox.Text = "";
        AddressBox.Text = "";
    }
    else 
    {
        MySqlConnection cs = new MySqlConnection(connectionSQL);
        cs.Open();

        DataSet ds = new DataSet();

        // You only need to select the address since you already have the name unless 
        // they are displayed differently and you want the database display to show
        MySqlDataAdapter da = new MySqlDataAdapter("Select address from Teacher WHERE name='" + comboBox1.Text + "'", cs);

        MySqlCommandBuilder cmd = new MySqlCommandBuilder(da);

        da.Fill(ds);

        NameBox.Text = comboBox1.Text;
        AddressBox.Text = ds.Tables[0].Rows[0]["address"].ToString();
    }
}

此外,如果名称在组合框中的显示方式与在数据库中的显示方式不同,这种方式很容易被忽略,例如名字和姓氏之间的额外空格或其他难以明显检测到的内容,这可能会导致查询不匹配。

于 2014-04-01T07:45:06.540 回答
0
AddressBox.DataBind();
NameBox.DataBind();
于 2014-02-14T13:48:17.817 回答