4

I have a table that populate Combobox1 and Combobox1 should populate Combobox2 and this is where the problem is. That's the exception i'm getting

The multi-part identifier "System.Data.DataRowView" could not be bound.

Code :

    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";
    }
4

1 回答 1

3

这是由于在第一个组合中填充数据时加载了第二个组合框。
您可以通过以下方式避免此错误:
1. 使用SelectionChangeCommitted事件而不是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;
}

希望这会对你有所帮助。

于 2013-04-18T07:18:25.133 回答