【问题标题】:Items in WinForms ComboBox not updating when DataSource values change当 DataSource 值更改时,WinForms ComboBox 中的项目不会更新
【发布时间】:2015-11-12 12:40:22
【问题描述】:

我有一个通过数据源绑定到列表的组合框。出于某种原因,当数据源项更改时,组合框中的项似乎不会自动更新。我可以在调试器中看到数据源包含正确的项目。

StackOverflow 上有很多关于此的答案,但大多数都没有答案,不适合我,或者需要从使用列表更改为 BindingLists,由于使用方法 BindingLists 的代码量很大,我无法执行此实例没有。

肯定有一种简单的方法来告诉 ComboBox 刷新它的项目吗?我不敢相信这不存在。我已经有一个在需要更新 Combo 时触发的事件,但我更新值的代码无效。

组合声明:

    this.devicePortCombo.DataBindings.Add(
             new System.Windows.Forms.Binding("SelectedValue", 
               this.deviceManagementModelBindingSource, "SelectedDevice", true,
               DataSourceUpdateMode.OnPropertyChanged));
    this.devicePortCombo.DataSource = this.availableDevicesBindingSource;

更新组合框的代码:

private void Instance_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "AvailableDevices")
    {
        // Rebind dropdown when available device list changes.
        this.Invoke((MethodInvoker)delegate
        {
            devicePortCombo.DataSource = AvailableDevicesList;
            devicePortCombo.DataBindings[0].ReadValue();
            devicePortCombo.Refresh();
        });
    }
}

【问题讨论】:

  • 如果您使用的是 BindingSource,您是否尝试过 BindingSource.ResetBindings() msdn.microsoft.com/en-us/library/…
  • 当我在必须将数据源设置为空之前遇到此问题时,然后重新添加它。
  • 但这可能会导致任何选定的值变为未设置,这与使用 BindingList 时的工作方式不同。

标签: c# winforms combobox


【解决方案1】:

您没有将 DataGridview 的 DataSource 绑定到第一次绑定的 this.availableDevicesBindingSource 的同一个 BindingSource 对象。但后来你绑定到不同的对象AvailableDevicesList。您再次为SelectedValue 使用另一个绑定源,即this.deviceManagementModelBindingSource

只使用一个BindingSource,可能会解决您的问题

【讨论】:

  • 谢谢 - 但我的问题来自 2 年前 :)
  • 您的问题没有答案,其他人可以从您的问题中寻求帮助。
猜你喜欢
  • 2011-11-14
  • 2013-11-30
  • 2018-09-15
  • 1970-01-01
  • 2019-11-07
  • 2011-04-27
  • 2013-10-11
  • 2021-09-26
  • 1970-01-01
相关资源
最近更新 更多