此Winforms项目出现问题。尝试在使用字典 propList 填充的combBox上使用SelectedIndexChanged事件:
comboBox1.DataSource = new BindingSource(propList, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
这是事件本身:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox comboBox = (ComboBox)sender;
//comboBox.DataSource = null;
System.Collections.Generic.KeyValuePair<int, string> dummy =
(System.Collections.Generic.KeyValuePair<int, string>)
comboBox.SelectedItem;
//comboBox1.DataSource = new BindingSource(propList, null);
PopulateCollars(dummy.Key);
}
然后将其抛出KeyValuePair演员:
Items collection cannot be modified when the DataSource property is set
我知道这是适当的演员,因为调试显示:
SelectedItem ~~~ object System.Collections.Generic.KeyValuePair<int,string>}
我的问题是,为什么显式演员会修改项目集合?在使用C ++时,强制转换不会修改他们正在投射的数据,这对我来说没有意义。
注意,使用注释掉的行会导致空引用异常,因为显然将数据源设置为null会擦除组合框中的所有成员。
答案 0 :(得分:0)
您是否有机会在PopulateCollars中修改dummy.Key
或dummy
?由于我从未见过演员改变对象的数据,这个例程似乎更可能是罪魁祸首。正如我在上面评论的那样,有时VS对于哪一行引发错误是完全错误的。
ETA:好的,那不是它。这是一个想法。检查异常的堆栈跟踪,看看您的方法和(在框架中)抛出异常的方法之间是否存在任何有趣的层。还要确保不会通过PopulateCollars中的某些内容递归调用此方法,这会导致列表发生更改。
如果您在处理组合框导致的更改时尝试将同一个组合框与其他数据一起使用,则可能无效。