teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

改善

2018/06/01 06:03

投稿

xlostdjx
xlostdjx

スコア39

title CHANGED
File without changes
body CHANGED
@@ -18,60 +18,49 @@
18
18
  {
19
19
  public partial class Form1 : Form
20
20
  {
21
- public Form1()
21
+ public class ItemSet
22
22
  {
23
+ // DisplayMemberとValueMemberにはプロパティで指定する仕組み
23
- InitializeComponent();
24
+ public String ItemDisp { get; set; }
24
- }
25
+ public int ItemValue { get; set; }
25
26
 
27
+ // プロパティをコンストラクタでセット
26
- private void Form1_Load(object sender, EventArgs e)
28
+ public ItemSet(int v, String s)
27
- {
29
+ {
28
-
30
+ ItemDisp = s;
31
+ ItemValue = v;
32
+ }
29
33
  }
30
- }
31
34
 
32
- class Sample
33
- {
34
- [STAThread]
35
- public static void Main()
35
+ public Form1()
36
36
  {
37
- Application.Run(new MainForm());
37
+ InitializeComponent();
38
- }
39
- }
40
38
 
41
- class MainForm : Form
42
- {
43
- private ComboBox comboBox = new ComboBox();//ボボック
39
+ // ComboBox用データ作成 //ListでOK //IList イターフェイまたは
44
- private Label lb = new Label(); //ラベル
45
- private Button bt = new Button(); //ボタン
40
+ //IListSource インターフェイスを実装する、DataSet または Array などのオブジェクト。
46
41
 
47
- public MainForm()
42
+ List<ItemSet> src = new List<ItemSet>();
48
- {
49
- //値の設定
43
+ src.Add(new ItemSet(1, "Number1"));/// 1つでItem1つ分となる
50
- comboBox.Items.Add("晴れ");
44
+ src.Add(new ItemSet(2, "Number2"));
51
- comboBox.Items.Add("曇り");
45
+ src.Add(new ItemSet(3, "Number3"));
52
- comboBox.Items.Add("雨");
53
46
 
47
+ // ComboBoxに表示と値をセット
48
+ comboBox1.DataSource = src;
49
+ comboBox1.DisplayMember = "ItemDisp";
54
- lb.Text = "";
50
+ comboBox1.ValueMember = "ItemValue";
55
- lb.AutoSize = true;
56
- lb.Top = comboBox.Bottom;
57
51
 
52
+ // 初期値セット
58
- bt.Text = "値を取得";
53
+ comboBox1.SelectedIndex = 0;
59
- bt.AutoSize = true;
54
+ comboBox1_SelectedIndexChanged(null, null);
60
- bt.Top = lb.Bottom;
55
+ }
61
56
 
62
- this.Controls.Add(comboBox);
63
- this.Controls.Add(lb);
64
- this.Controls.Add(bt);
65
57
 
66
- bt.Click += new EventHandler(bt_Click);
67
- }
68
- public void bt_Click(Object sender, EventArgs e)
58
+ private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
69
59
  {
60
+ // labelに現在コンボ選択の内容を表示
61
+ ItemSet tmp = ((ItemSet)comboBox1.SelectedItem);//表示名はキャストして取りだす
70
- lb.Text = "";
62
+ labelDisplay.Text = tmp.ItemDisp;
71
- //値を取得
72
- lb.Text += comboBox.SelectedItem.ToString();
63
+ labelValue.Text = comboBox1.SelectedValue.ToString();//値はそのまま取りだせる
64
+
73
65
  }
74
- }
75
-
76
- }
77
66
  ```

1

編集

2018/06/01 06:03

投稿

xlostdjx
xlostdjx

スコア39

title CHANGED
File without changes
body CHANGED
@@ -1,9 +1,8 @@
1
- ```C#
1
+ C#
2
2
 
3
3
  このようにコード書いてみたのですが動きません。
4
-  
4
+  ```
5
5
  コード
6
- ```
7
6
 
8
7
  using System;
9
8
  using System.Collections.Generic;
@@ -74,4 +73,5 @@
74
73
  }
75
74
  }
76
75
 
77
- }
76
+ }
77
+ ```