Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9749

コンボボックスに表示名と値を入れる

$
0
0

ComboBoxにおいて表示名と値を関連付ける

cmb.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespaceComboBoxDispalyValue{publicpartialclassForm1:Form{publicclassItemSet{// DisplayMemberとValueMemberにはプロパティで指定する仕組みpublicStringItemDisp{get;set;}publicintItemValue{get;set;}// プロパティをコンストラクタでセットpublicItemSet(intv,Strings){ItemDisp=s;ItemValue=v;}}publicForm1(){InitializeComponent();// ComboBox用データ作成 //ListでOK //IList インターフェイスまたは IListSource インターフェイスを実装する、DataSet または Array などのオブジェクト。List<ItemSet>src=newList<ItemSet>();src.Add(newItemSet(100,"Number1"));/// 1つでItem1つ分となるsrc.Add(newItemSet(200,"Number2"));src.Add(newItemSet(300,"Number3"));// ComboBoxに表示と値をセットcomboBox1.DataSource=src;comboBox1.DisplayMember="ItemDisp";comboBox1.ValueMember="ItemValue";// 初期値セットcomboBox1.SelectedIndex=0;comboBox1_SelectedIndexChanged(null,null);}privatevoidcomboBox1_SelectedIndexChanged(objectsender,EventArgse){// labelに現在コンボ選択の内容を表示ItemSettmp=((ItemSet)comboBox1.SelectedItem);//表示名はキャストして取りだすlabelDisplay.Text=tmp.ItemDisp;labelValue.Text=comboBox1.SelectedValue.ToString();//値はそのまま取りだせる}}}

結果

実行すると下記の様に表示される
20200704_Combbox_表示名と値を入れる.png


Viewing all articles
Browse latest Browse all 9749

Trending Articles