Use binding list to operate ComboBox
This article describes how to bind a list of custom class objects to the ComboBox control. Here is the solution:
First, modify the Country
class and add a constructor to initialize the Name
and Cities
properties:
public class Country { public string Name { get; set; } public IList<City> Cities { get; set; } public Country(string name) { Name = name; Cities = new List<City>(); } }
Create Country
list of objects:
List<Country> countries = new List<Country> { new Country("英国"), new Country("澳大利亚"), new Country("法国") };
Initialize BindingSource
and set it DataSource
to a list of countries:
var bindingSource1 = new BindingSource(); bindingSource1.DataSource = countries;
Bind ComboBox's DataSource
to BindingSource
's DataSource
:
comboBox1.DataSource = bindingSource1.DataSource;
Set ComboBox's DisplayMember
and ValueMember
to the corresponding attributes of the Country
class:
comboBox1.DisplayMember = "Name"; comboBox1.ValueMember = "Name";
ComboBox will now display the names of each country in the list. To retrieve the selected country, you can use the SelectedItem
attribute of the ComboBox:
Country selectedCountry = (Country)comboBox1.SelectedItem;
Note that for dynamic updates, your data structure should implement the IBindingList
interface. It is recommended to use BindingList<T>
.
Be sure to bind DisplayMember
to a property rather than a public field to ensure correct display and functionality.
The above is the detailed content of How to Bind a Custom Class List to a ComboBox in C#?. For more information, please follow other related articles on the PHP Chinese website!