データーソースを利用することによりコンボボックスでリスト化されたクラスからプロパティを取り出せる
このリストにはアイテムの追加編集が簡単に可能で変更はフォームに反映される
プロパティには様々な型が利用できるのでデリゲートも可能と思われる
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
BindingList<Person> personList; //バインドさせるリスト
public Form1()
{
personList = new BindingList<Person>();
personList.Add(new Person("Taro", 15, "tokyo"));
personList.Add(new Person("Yoshida", 23, "osaka"));
personList.Add(new Person("Kazuya", 8, "Kyusyu"));
InitializeComponent();
comboBox1.DataSource = personList; //データソースの登録
comboBox1.DisplayMember = "Name"; //プロパティの名前からコンボボックスに表示するメンバーを設定
personList.Add(new Person("Ueda", 2, "Sendai")); //どんなタイミングでもListとして項目に対し追加や編集ができる
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Person p = (Person)comboBox1.SelectedItem; //アイテム取り出し
label1.Text = p.Adress;
}
}
class Person
{
public string Name { get; set; }
public int ID { get; set; }
public string Adress { get; set; }
public Person(string name, int id, string adresss)
{
Name = name;
ID = id;
Adress = adresss;
}
}
}
最終更新:2012年08月14日 14:28