【C#】ComboBoxのデータソースにディクショナリを設定したい
コンボボックスのデータソースに、ディクショナリを設定します。
また、ディクショナリはアプリケーション構成ファイル(App.config)から作成します。
①アプリケーション構成ファイルにディクショナリの素を定義します。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8" ?> | |
<configuration> | |
<configSections> | |
<section name="SourceList" type="System.Configuration.NameValueFileSectionHandler" restartOnExternalChanges="false"/> | |
</configSections> | |
<SourceList> | |
<add key="選択アイテム1" value="select item 1" /> | |
<add key="選択アイテム2" value="select item 2" /> | |
<add key="選択アイテム3" value="select item 3" /> | |
</SourceList> | |
</configuration> |
②アプリケーション構成ファイルからディクショナリに設定します。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 設定ファイルからコンボボックスのデータソースを取得して、ディクショナリに格納します。 | |
var sources = (NameValueCollection)ConfigurationManager.GetSection("SourceList"); | |
foreach(string item in sources) | |
{ | |
ComboboxSource.Add(item, sources[item]); | |
} |
※ディクショナリ(ComboboxSource)は別の場所で定義しています。
③コンボボックスにディクショナリを設定します。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ディクショナリをコンボボックスに設定します。 | |
ComboBox1.DataSource = ComboboxSource.ToList(); | |
ComboBox1.DisplayMember = "key"; | |
ComboBox1.ValueMember = "value"; |
※DataSourceはIListを実装しているか、Array系でないと設定できないため、List変換します。
④コンボボックスで選択されたvalueを取得します。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Label1.Text = $"value -> {ComboBox1.SelectedValue}"; |
※単純にSelectedValueでOK。
コメント
コメントを投稿