c# - 当 DataSource 值更改时,WinForms ComboBox 中的项目不更新

标签 c# winforms combobox

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

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

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

组合声明:

    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();
        });
    }
}

最佳答案

在您的案例 this.availableDevicesBindingSource 中,您没有将 DataGridview 的 DataSource 绑定(bind)到相同的 BindingSource 对象,这是第一次绑定(bind)。但稍后您将绑定(bind)到不同的对象 AvailableDevicesList。您再次为 SelectedValue 使用另一个绑定(bind)源,即 this.deviceManagementModelBindingSource

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

关于c# - 当 DataSource 值更改时,WinForms ComboBox 中的项目不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32091689/

相关文章:

c# - 银光错误 0x17E0

c# - 未找到匹配命令 'dotnet-aspnet-codegenerator' 的可执行文件“

vb.net 将 datagridview 列类型更改为组合框

php - 数据库组合框用值填充输入框,然后在新浏览器窗口中打开 URL

c# - 包含由列和行字符串索引索引的数据的数据结构

c# - 从远程 SQL Server 获取备份

C# 使用滚动条控件/事件(没有文本框或窗口滚动)

c# - 如何在 C# 中使用箭头禁用 WinForm 上的导航?

c# - 如何检测C#表单中是否按下了多个键

javascript - 如何从组合框选定的记录中获取所有值?