如何将列表绑定到combobox? (的Winforms)

我想连接一个绑定源到类对象的列表,然后对象值的combobox任何人都可以build议如何做到这一点

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

是我的类,我想绑定它的名称字段绑定源,然后可以与一个combobox相关联

正如你指的是一个combobox,我假设你不想使用双向数据绑定(如果是的话,看看使用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") }; bindingSource1.DataSource = countries; comboBox1.DataSource = bindingSource1.DataSource; comboBox1.DisplayMember = "Name"; comboBox1.ValueMember = "Name"; 

对于背景,有两种使用ComboBox / ListBox的方法

1)将Country对象添加到Items属性中,并将Country检索为Selecteditem。 要使用这个,你应该重写国家的ToString。

2)使用DataBinding,将数据源设置为IList(List <>)并使用DisplayMember,ValueMember和SelectedValue

对于2)你将需要一个国家的名单第一

 // not tested, schematic: List<Country> countries = ...; ...; // fill comboBox1.DataSource = countries; comboBox1.DisplayMember="Name"; comboBox1.ValueMember="Cities"; 

然后在SelectionChanged中,

 if (comboBox1.Selecteditem != null) { comboBox2.DataSource=comboBox1.SelectedValue; } 
 public MainWindow(){ List<person> personList = new List<person>(); personList.Add(new person { name = "rob", age = 32 } ); personList.Add(new person { name = "annie", age = 24 } ); personList.Add(new person { name = "paul", age = 19 } ); comboBox1.DataSource = personList; comboBox1.DisplayMember = "name"; comboBox1.SelectionChanged += new SelectionChangedEventHandler(comboBox1_SelectionChanged); } void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) { person selectedPerson = comboBox1.SelectedItem as person; messageBox.Show(selectedPerson.name, "caption goes here"); } 

繁荣。

尝试这样的事情:

 yourControl.DataSource = countryInstance.Cities; 

如果您使用WebForms,则需要添加以下行:

 yourControl.DataBind(); 
 public class Country { public string Name { get; set; } public IList<City> Cities { get; set; } public Country() { Cities = new List<City>(); } } public class City { public string Name { get; set; } } List<Country> Countries = new List<Country> { new Country { Name = "Germany", Cities = { new City {Name = "Berlin"}, new City {Name = "Hamburg"} } }, new Country { Name = "England", Cities = { new City {Name = "London"}, new City {Name = "Birmingham"} } } }; bindingSource1.DataSource = Countries; member_CountryComboBox.DataSource = bindingSource1.DataSource; member_CountryComboBox.DisplayMember = "Name"; member_CountryComboBox.ValueMember = "Name"; 

这是我现在使用的代码

如果您正在使用ToolStripComboBox,则没有公开DataSource(.NET 4.0):

 List<string> someList = new List<string>(); someList.Add("value"); someList.Add("value"); someList.Add("value"); toolStripComboBox1.Items.AddRange(someList.ToArray());