LoginSignup
1
3

More than 3 years have passed since last update.

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

Posted at

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();//値はそのまま取りだせる
        }
    }
}

結果

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

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3