バインディング リストを使用して ComboBox を操作します
この記事では、カスタム クラス オブジェクトのリストを ComboBox コントロールにバインドする方法について説明します。解決策は次のとおりです:
まず、Country
クラスを変更し、Name
プロパティと Cities
プロパティを初期化するコンストラクターを追加します。
public class Country { public string Name { get; set; } public IList<City> Cities { get; set; } public Country(string name) { Name = name; Cities = new List<City>(); } }
オブジェクトの Country
リストを作成します:
List<Country> countries = new List<Country> { new Country("英国"), new Country("澳大利亚"), new Country("法国") };
BindingSource
を初期化して、DataSource
を国のリストに設定します:
var bindingSource1 = new BindingSource(); bindingSource1.DataSource = countries;
ComboBox の DataSource
を BindingSource
の DataSource
にバインドします:
comboBox1.DataSource = bindingSource1.DataSource;
ComboBox の DisplayMember
と ValueMember
を Country
クラスの対応する属性に設定します:
comboBox1.DisplayMember = "Name"; comboBox1.ValueMember = "Name";
ComboBox にはリスト内の各国の名前が表示されます。選択した国を取得するには、コンボボックスの SelectedItem
属性を使用できます:
Country selectedCountry = (Country)comboBox1.SelectedItem;
動的更新の場合、データ構造は IBindingList
インターフェースを実装する必要があることに注意してください。 BindingList<T>
を使用することをお勧めします。
正しい表示と機能を確保するには、DisplayMember
をパブリック フィールドではなくプロパティにバインドしてください。
以上がC# でカスタム クラス リストを ComboBox にバインドする方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。