我想将 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/