Bind a list of objects to a combo box option
You need a solution to bind a custom object list to a combobox and display its specified properties as option labels. As background, consider the following classes:
public class Country { public string Name { get; set; } public IList<City> Cities { get; set; } public Country() { Cities = new List<City>(); } }
Step-by-step guide
To create a binding, follow these steps:
Create a List
List<Country> countries = new List<Country> { new Country { Name = "UK" }, new Country { Name = "Australia" }, new Country { Name = "France" } };
Initialize a BindingSource and assign its DataSource to List
var bindingSource1 = new BindingSource(); bindingSource1.DataSource = countries;
Set the DataSource of the combo box to the DataSource of the BindingSource:
comboBox1.DataSource = bindingSource1.DataSource;
Specify the property to be displayed in the combo box as DisplayMember:
comboBox1.DisplayMember = "Name";
Specifies that the value returned by the combo box will use the property as ValueMember:
comboBox1.ValueMember = "Name";
Retrieve selected items
To get the selected Country object from a combo box, cast its selected items to the corresponding type:
Country selectedCountry = (Country)comboBox1.SelectedItem;
Dynamic updates
If you need the combo box to update automatically, make sure the DataSource implements the IBindingList interface. BindingList
Display objects and properties
Note that DisplayMember should reference a property in the class (e.g., "Name"). If you use a field (for example, "Name;"), the value will not be accessible and the combo box will display the object type instead of the property value.
The above is the detailed content of How to Bind a List of Custom Objects to a ComboBox and Retrieve the Selected Item?. For more information, please follow other related articles on the PHP Chinese website!