Home >Backend Development >C++ >How to Bind a Custom Class List to a ComboBox in C#?
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:
<code class="language-csharp">public class Country { public string Name { get; set; } public IList<City> Cities { get; set; } public Country(string name) { Name = name; Cities = new List<City>(); } }</code>
Create Country
list of objects:
<code class="language-csharp">List<Country> countries = new List<Country> { new Country("英国"), new Country("澳大利亚"), new Country("法国") };</code>
Initialize BindingSource
and set it DataSource
to a list of countries:
<code class="language-csharp">var bindingSource1 = new BindingSource(); bindingSource1.DataSource = countries;</code>
Bind ComboBox's DataSource
to BindingSource
's DataSource
:
<code class="language-csharp">comboBox1.DataSource = bindingSource1.DataSource;</code>
Set ComboBox's DisplayMember
and ValueMember
to the corresponding attributes of the Country
class:
<code class="language-csharp">comboBox1.DisplayMember = "Name"; comboBox1.ValueMember = "Name";</code>
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:
<code class="language-csharp">Country selectedCountry = (Country)comboBox1.SelectedItem;</code>
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!