C# 用组合框选择c中的mysql数据值填充文本框
我试图用数据库中的值填充文本框,因此当用户从组合框中选择教师姓名时,文本框将填充他们的联系人详细信息。这是我目前掌握的代码。没有错误,但是当我从组合框中选择一个值时,文本框仍然为空C# 用组合框选择c中的mysql数据值填充文本框,c#,mysql,combobox,textbox,populate,C#,Mysql,Combobox,Textbox,Populate,我试图用数据库中的值填充文本框,因此当用户从组合框中选择教师姓名时,文本框将填充他们的联系人详细信息。这是我目前掌握的代码。没有错误,但是当我从组合框中选择一个值时,文本框仍然为空 private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) { MySqlConnection cs = new MySqlConnection(connectionSQL);
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)
如果列表中只有一个项目或用户选择了第一个项目,则查询将运行,但文本框不会填充。在验证所选索引之前,您正在查询数据库,并且应该检查大于-1而不是0的所选索引
AddressBox.DataBind();
NameBox.DataBind();
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();
}
}
此外,如果名称在组合框中的显示方式与在数据库中的显示方式不同,很容易被忽略,例如名字和姓氏之间有额外的空格或其他难以明显检测的内容,则可能会导致查询不匹配。WinForms,WPF,ASP.NET?我修改了代码,现在它抛出了这个未设置为对象实例的实例对象引用。我检查了一下,发现我的数据集似乎是空的,尽管所有的信息都是空的correct@user2187795,在哪条线上?当您在调试器中时,以下哪一项为空:NameBox、AddressBox、ds、Tables[0]、Rows[0]、Rows[0][name]或Rows[0][address]?@user2187795,请帮我一个忙,将您的SELECT语句更改为SELECT name,address FROM THEER WHERE。这并不能提供问题的答案。若要评论或要求作者澄清,请在其帖子下方留下评论-您可以随时对自己的帖子发表评论,一旦您有足够的评论,您就可以发表评论。将值分配给textbox后,使用DataBind方法将数据库中的值绑定到textbox。