如何将列表绑定到组合框? [英] How to bind a List to a 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
推荐答案
当您提到组合框时,我假设您不想使用 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
.
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
绑定到类上的属性而不是公共字段.如果你的班级使用 public string 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.
这篇关于如何将列表绑定到组合框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!