如何将列表绑定到ComboBox? [英] How to bind a List to a ComboBox?

查看:93
本文介绍了如何将列表绑定到ComboBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 BindingSource 连接到类对象列表,然后将对象值连接到ComboBox。

任何人都可以建议如何做?

I want to connect a BindingSource to a list of class objects and then objects value to a ComboBox.
Can anyone suggest how to do it?

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

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

是我的课程,我想绑定其 name 字段到BindingSource,然后可以将其与ComboBox关联

is my class and I want to bind its name field to a BindingSource which could be then associated with a ComboBox

推荐答案

As您指的是组合框,我假设您不想使用2向数据绑定(如果是,请使用 BindingList

As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a 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";

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

To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1.SelectedItem;.

如果您希望ComboBox动态更新,则需要确保您设置为 DataSource 的数据结构实现 IBindingList ;这样的结构之一就是 BindingList< T>

If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the DataSource implements IBindingList; one such structure is BindingList<T>.

提示:确保将 DisplayMember 绑定到类的Property而不是公共字段。如果您的课程使用公用字符串Name {get;组; } 可以使用,但是如果使用 public string Name; 则无法访问该值,而是显示每个对象的类型组合框中的行。

Tip: make sure that you are binding the DisplayMember to a Property on the class and not a public field. If you class uses public string Name { get; set; } it will work but if it uses public string Name; it will not be able to access the value and instead will display the object type for each line in the combo box.

这篇关于如何将列表绑定到ComboBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆