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:
<code class="language-c#">public class Country { public string Name { get; set; } public IList<City> Cities { get; set; } public Country() { Cities = new List<City>(); } }</code>
Step-by-step guide
To create a binding, follow these steps:
Create a List
<code class="language-c#"> List<Country> countries = new List<Country> { new Country { Name = "UK" }, new Country { Name = "Australia" }, new Country { Name = "France" } };</code>
Initialize a BindingSource and assign its DataSource to List
<code class="language-c#"> var bindingSource1 = new BindingSource(); bindingSource1.DataSource = countries;</code>
Set the DataSource of the combo box to the DataSource of the BindingSource:
<code class="language-c#"> comboBox1.DataSource = bindingSource1.DataSource;</code>
Specify the property to be displayed in the combo box as DisplayMember:
<code class="language-c#"> comboBox1.DisplayMember = "Name";</code>
Specifies that the value returned by the combo box will use the property as ValueMember:
<code class="language-c#"> comboBox1.ValueMember = "Name";</code>
Retrieve selected items
To get the selected Country object from a combo box, cast its selected items to the corresponding type:
<code class="language-c#">Country selectedCountry = (Country)comboBox1.SelectedItem;</code>
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!