C# ComboBox データ バインディング: オブジェクトのリストの表示
このガイドでは、C# ComboBox にオブジェクトのリストを入力し、各オブジェクトの特定のプロパティ (「名前」など) をドロップダウンの項目として表示する方法を説明します。 BindingSource
を使用してデータ接続を管理します。
ステップ 1: データ クラスとリストの定義
まず、ComboBox で表現したいプロパティを含むクラス (例: Country
) を作成します。 Name
プロパティと City
オブジェクトのリストの例を次に示します。
public class Country { public string Name { get; set; } public IList<City> Cities { get; set; } = new List<City>(); } public class City { public string Name { get; set; } }
次に、Country
オブジェクトのリストを作成します。
List<Country> countries = new List<Country>() { new Country { Name = "UK" }, new Country { Name = "Australia" }, new Country { Name = "France" } };
ステップ 2: BindingSource のセットアップ
BindingSource
オブジェクトを作成し、countries
リストをそのデータ ソースとして割り当てます。
BindingSource bindingSource = new BindingSource(); bindingSource.DataSource = countries;
ステップ 3: BindingSource を ComboBox に接続する
BindingSource
をコンボボックスにリンクします:
comboBox1.DataSource = bindingSource;
ステップ 4: 表示メンバーと値メンバーの構成
ComboBox ドロップダウンに表示するプロパティ (DisplayMember
) と項目が選択されたときに取得するプロパティ (ValueMember
) を指定します。
comboBox1.DisplayMember = "Name"; comboBox1.ValueMember = "Name"; // Or another suitable property if needed
ステップ 5: 選択した項目へのアクセス
選択した Country
オブジェクトを取得するには:
Country selectedCountry = (Country)comboBox1.SelectedItem;
動的更新の処理 (IBindingList)
動的更新 (リストへの項目の追加または削除) の場合は、データ ソースが IBindingList
インターフェイスを実装していることを確認してください。 BindingList<T>
は良い選択です:
BindingList<Country> countries = new BindingList<Country>() { /* ... your countries ... */ }; bindingSource.DataSource = countries;
このアプローチにより、基になる countries
リストへの変更が ComboBox に自動的に反映されます。
以上がC# でオブジェクトのリストを ComboBox にバインドするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。