使用组合框选择c#中的mysql数据值填充文本框

时间:2013-04-03 17:03:42

标签: c# mysql combobox textbox populate

我正在尝试使用数据库中的值填充文本框,因此当用户从组合框中选择教师的名称时,文本框将填充其联系人详细信息。这是我到目前为止的代码。没有错误,但是当我从组合框中选择一个值时,文本框仍然是空白的。

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

        }

非常感谢任何帮助或建议

3 个答案:

答案 0 :(得分:0)

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

if (comboBox1.SelectedIndex > 0)

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

答案 1 :(得分:0)

AddressBox.DataBind();
NameBox.DataBind();

答案 2 :(得分: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();
    }
}

此外,如果名称在组合框中的显示方式与数据库中显示的方式相差很容易,例如名字和姓氏之间的额外空格或其他难以察觉的空间,则可能导致查询不匹配。