我有一个字符串列表,它是BindingSource对象的DataSource,它转而是ComboBox的DataSource。
当我更改List(添加或删除字符串)时,我调用BindingSource上的ResetBindings()方法。这会按预期更新ComboBox中的项目,但它也会将SelectedIndex设置为“0”,而不是未初始化的值“-1”。我想在不初始化ComboBox的情况下更新项目
我已经尝试在SelectedIndexChanged事件处理程序中处理它,如下所示:
private void cmbSelectxx_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
if (!cmb.Focused)
{
cmb.SelectedIndexChanged -= new EventHandler(cmbSelectxx_SelectedIndexChanged);
cmb.SelectedIndex = -1;
cmb.ResetText();
cmb.SelectedText = "";
cmb.SelectedIndexChanged += new EventHandler(cmbSelectxx_SelectedIndexChanged);
return;
}
//...
}
但这并没有解决我的问题
将控制绑定到数据代码:
bs = new BindingSource();
bs.DataSource = SomeList;
cmbSelectxx.DataSource = bs;
直接在BindingSource
而不是SomeList
上执行添加/删除操作。这些添加/删除操作传播回SomeList
。 '请注意,如果删除ComboBox中当前选定的项,它将更新为最合适的值。
假设你的SomeList
包含值“a”,“b”,“c”,“d”。
BindingSource
中移除,则ComboBox.SelectedItem
将变为“c”。BindingSource
中删除“a”,则ComboBox.SelectedItem
不会改变。ComboBox.SelectedItem
将变为“c”。