[英]Populating textbox with mysql data values from combobox selection c#
我试图用数据库中的值填充文本框,以便当用户从组合框中选择教师姓名时,文本框将填充其联系方式。 这是我到目前为止的代码。 没有错误,但是当我从组合框中选择一个值时,文本框仍然为空白。
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();
}
任何帮助或建议,将不胜感激
我必须相信,根据您的代码,问题就在这里:
if (comboBox1.SelectedIndex > 0)
如果列表中只有一个项目, 或者用户选择了第一个项目,则查询将运行,但不会填充文本框。
AddressBox.DataBind();
NameBox.DataBind();
在验证所选索引之前,您正在查询数据库,并且应该检查所选索引是否大于-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();
}
}
另外,如果名称在组合框中的显示方式与数据库中显示的方式不同,则很容易错过,例如名字和姓氏之间有多余的空格,或者其他很难看到的东西,可能导致查询不匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.