c# - 如何将列表绑定(bind)到组合框?

标签 c# winforms data-binding combobox

我想将 BindingSource 连接到类对象列表,然后将对象值连接到 ComboBox。
谁能建议怎么做?

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }

    public Country()
    {
        Cities = new List<City>();
    }
}

是我的类(class),我想将其 name 字段绑定(bind)到 BindingSource,然后可以将其与 ComboBox 关联

最佳答案

由于您指的是组合框,我假设您不想使用双向数据绑定(bind)(如果是这样,请考虑使用 BindingList )

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }
    public Country(string _name)
    {
        Cities = new List<City>();
        Name = _name;
    }
}



List<Country> countries = new List<Country> { new Country("UK"), 
                                     new Country("Australia"), 
                                     new Country("France") };

var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;

comboBox1.DataSource = bindingSource1.DataSource;

comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";

要查找在绑定(bind)组合框中选择的国家/地区,您可以执行以下操作:Country country = (Country)comboBox1.SelectedItem; .

如果您希望 ComboBox 动态更新,您需要确保您设置为 DataSource 的数据结构。工具 IBindingList ;一个这样的结构是 BindingList<T> .


提示:确保您绑定(bind)了 DisplayMember到类上的属性而不是公共(public)字段。如果你上课使用 public string Name { get; set; }它会工作,但如果它使用 public string Name;它将无法访问该值,而是会在组合框中显示每一行的对象类型。

关于c# - 如何将列表绑定(bind)到组合框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/600869/

相关文章:

java - 将 Swing 组件绑定(bind)到 Java 对象

WPF:绑定(bind)到我的自定义控件不会更新

c# - 如何为 Controller 创建我自己的 http 上下文?

c# - Steam 授权

c# - 如何将外部 .exe 添加到我的 C# 项目中?

c# - 向程序发送击键

c# - 即使关闭 WPF 跟踪设置,奇怪的资源字典警告也会出现在输出窗口中

c# - 如何将数据传递到 `OnActivateAsync()` 以初始化我的有状态 actor?

c# - 如何使用 LINQ 查找 DataGridView 行?

javascript - 绑定(bind) html 时不会发生 knockout 表单提交