Bind the list of class objects to the ComboBox control
If you have a list of class objects and want to bind it to a ComboBox control, follow these steps:
1. Create your class
Suppose there is a class representing a country:
<code class="language-csharp">public class Country { public string Name { get; set; } public IList<city> Cities { get; set; } public Country() { Cities = new List<city>(); } }</code>
2. Create BindingSource object
Create a BindingSource object and set its DataSource property to your list of countries. For example:
<code class="language-csharp">var countries = new List<Country> { new Country { Name = "UK" }, new Country { Name = "Australia" }, new Country { Name = "France" } }; var bindingSource1 = new BindingSource(); bindingSource1.DataSource = countries;</code>
3. Set the data source of ComboBox
Set the DataSource property of the ComboBox to the DataSource property of the BindingSource object. This will establish a connection between the ComboBox and your list.
<code class="language-csharp">comboBox1.DataSource = bindingSource1.DataSource;</code>
4. Set DisplayMember and ValueMember properties
Specify the class attribute to be displayed in the ComboBox and the attribute to be stored as the selected value. Use DisplayMember to set display properties and ValueMember to set value properties:
<code class="language-csharp">comboBox1.DisplayMember = "Name"; comboBox1.ValueMember = "Name";</code>
5. Get the selected item
To access the selected country, cast the ComboBox's SelectedItem property to your class type:
<code class="language-csharp">Country country = (Country)comboBox1.SelectedItem;</code>
Tips:
The above is the detailed content of How to Bind a List of Class Objects to a ComboBox in C#?. For more information, please follow other related articles on the PHP Chinese website!