多部分标识符“system . data . datarowview”;不能被束缚
本文关键字:不能 束缚 datarowview data 标识符 system 多部 | 更新日期: 2023-09-27 18:09:51
我有一个填充Combobox1的表,Combobox1应该填充Combobox2,这就是问题所在。这是我得到的例外
代码:多部分标识符"System.Data. net"。无法绑定DataRowView。
private void frm2_Load(object sender, EventArgs e)
{
//Populate Combobox1
SqlDataAdapter da = new SqlDataAdapter("SELECT CategoryID, Name FROM Categories", clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "CategoryID";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//populate Combobox2
SqlDataAdapter da = new SqlDataAdapter("SELECT SubCategoryID, Name FROM SubCategories WHERE CategoryID=" + comboBox1.SelectedValue, clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
comboBox2.DataSource = ds.Tables[0];
comboBox2.DisplayMember = "Name";
comboBox2.ValueMember = "SubCategoryID";
}
这是由于在第一个组合中填充数据时加载第二个组合框。
您可以通过以下方式避免此错误:
1. 使用 selectionchangecomcommitted 事件代替SelectedIndexChanged事件。
或
2. 分离选定的索引更改事件,填充组合框,再次将事件附加为:
private void frm2_Load(object sender, EventArgs e)
{
//Detach event
comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged;
//Populate Combobox1
SqlDataAdapter da = new SqlDataAdapter("SELECT CategoryID, Name FROM Categories", clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "CategoryID";
//Attach event again
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
}