如何将列表绑定到ComboBox?

编程入门 行业动态 更新时间:2024-10-27 23:18:56
本文介绍了如何将列表绑定到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?

本文发布于:2023-11-12 23:25:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582799.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   如何将   列表   ComboBox

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!