【问题标题】:Calling ResetBindings on bindingsource to update ComboBox results in initialising control, how to update items without initialising?在 bindingsource 上调用 ResetBindings 以更新 ComboBox 导致初始化控件,如何在不初始化的情况下更新项目?
【发布时间】:2019-04-04 09:55:43
【问题描述】:

我有一个字符串列表,它是 BindingSource 对象的 DataSource,而后者又是 ComboBox 的 DataSource。

当我更改列表(添加或删除字符串)时,我在 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】:

    直接在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”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多