例
ComboBoxにおいて表示名と値を関連付ける
cmb.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ComboBoxDispalyValue
{
public partial class Form1 : Form
{
public class ItemSet{
// DisplayMemberとValueMemberにはプロパティで指定する仕組み
public String ItemDisp { get; set; }
public int ItemValue { get; set; }
// プロパティをコンストラクタでセット
public ItemSet(int v, String s){
ItemDisp = s;
ItemValue = v;
}
}
public Form1()
{
InitializeComponent();
// ComboBox用データ作成 //ListでOK //IList インターフェイスまたは IListSource インターフェイスを実装する、DataSet または Array などのオブジェクト。
List<ItemSet> src = new List<ItemSet>();
src.Add(new ItemSet(100, "Number1"));/// 1つでItem1つ分となる
src.Add(new ItemSet(200, "Number2"));
src.Add(new ItemSet(300, "Number3"));
// ComboBoxに表示と値をセット
comboBox1.DataSource = src;
comboBox1.DisplayMember = "ItemDisp";
comboBox1.ValueMember = "ItemValue";
// 初期値セット
comboBox1.SelectedIndex = 0;
comboBox1_SelectedIndexChanged(null, null);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// labelに現在コンボ選択の内容を表示
ItemSet tmp = ((ItemSet)comboBox1.SelectedItem);//表示名はキャストして取りだす
labelDisplay.Text = tmp.ItemDisp;
labelValue.Text = comboBox1.SelectedValue.ToString();//値はそのまま取りだせる
}
}
}