当DataSource值更改时,WinForms ComboBox中的项不会更新

时间:2015-08-19 09:33:30

标签: c# winforms combobox

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

StackOverflow上有很多关于此问题的答案,但大多数答案都没有答案,对我不起作用,或者需要从使用Lists更改为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();
        });
    }
}

1 个答案:

答案 0 :(得分:1)

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

仅使用一个BindingSource,可以解决您的问题

相关问题