Home > Backend Development > C++ > How to Bind a Custom Class List to a ComboBox in C#?

How to Bind a Custom Class List to a ComboBox in C#?

DDD
Release: 2025-01-13 09:29:43
Original
650 people have browsed it

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>
Copy after login

Create Country list of objects:

<code class="language-csharp">List<Country> countries = new List<Country>
{
    new Country("英国"),
    new Country("澳大利亚"),
    new Country("法国")
};</code>
Copy after login

Initialize BindingSource and set it DataSource to a list of countries:

<code class="language-csharp">var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;</code>
Copy after login

Bind ComboBox's DataSource to BindingSource's DataSource:

<code class="language-csharp">comboBox1.DataSource = bindingSource1.DataSource;</code>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template