在bindingsource上调用ResetBindings来更新ComboBox会导致初始化控制,如何在不初始化的情况下更新项目?

问题描述 投票:0回答:1

我有一个字符串列表,它是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;
c# winforms data-binding
1个回答
0
投票

直接在BindingSource而不是SomeList上执行添加/删除操作。这些添加/删除操作传播回SomeList。 '请注意,如果删除ComboBox中当前选定的项,它将更新为最合适的值。

假设你的SomeList包含值“a”,“b”,“c”,“d”。

  1. 如果选择“b”并将其从BindingSource中移除,则ComboBox.SelectedItem将变为“c”。
  2. 如果选择“b”并从BindingSource中删除“a”,则ComboBox.SelectedItem不会改变。
  3. 如果选择“d”然后删除,则ComboBox.SelectedItem将变为“c”。
© www.soinside.com 2019 - 2024. All rights reserved.