ASP.NETのWebフォームを使っていると、DropDownListコンポーネントはよく使う。
DropDownListには、いくつかデータのセット方法がある。
直接aspxファイル上に書く
変わらない値なら、これで十分。
<asp:DropDownList ID="DropDownList0" runat="server"> <asp:ListItem Value="4">April</asp:ListItem> <asp:ListItem Value="5">May</asp:ListItem> <asp:ListItem Value="6">June</asp:ListItem> </asp:DropDownList>
ListItemクラスを追加する
コード側で、ちゃちゃっと追加する場合などに。
//ListItemを追加 this.DropDownList1.Items.Clear(); this.DropDownList1.Items.Add(new ListItem("4月", "4")); this.DropDownList1.Items.Add(new ListItem("5月", "5")); this.DropDownList1.Items.Add(new ListItem("6月", "6"));
バインド(Bind)する
そして、データバインド機能。
DictionaryをBind
キー、バリューな、DictinaryにはDropDownListは相性がいい気がする。
DataTextFiledとDataValueFieldに、Dicionaryの中身であるKeyValuePairのプロパティ名を入れる。
(入れない場合、[卯月,4] といった感じでセットでTextとValueに入る。)
//DictionaryをBind var dic = new Dictionary<string,int>(); dic.Add("卯月", 4); dic.Add("皐月", 5); dic.Add("水無月", 6); this.DropDownList2.DataSource = dic; this.DropDownList2.DataTextField = "Key"; this.DropDownList2.DataValueField = "Value"; this.DropDownList2.DataBind();
ListをBind
Listもバインドできる。ちなみに、TextもValueも同じ値になる。
//ListをBind var list = new List<String>(); list.Add("April"); list.Add("May"); list.Add("June"); this.DropDownList3.DataSource = list; this.DropDownList3.DataBind();
DataTableをバインド
例では、その場でDataTable作ってるけど、SQLで取得したテーブルをバインドするときに使える。
//DataTableをバインド var dt = new DataTable(); dt.Columns.Add("name", typeof(string)); dt.Columns.Add("age", typeof(int)); var newRow = dt.NewRow(); newRow["name"] = "yamada"; newRow["age"] = 20; dt.Rows.Add(newRow); newRow = dt.NewRow(); newRow["name"] = "suzuki"; newRow["age"] = 25; dt.Rows.Add(newRow); this.DropDownList5.DataSource = dt; this.DropDownList5.DataTextField = "name"; this.DropDownList5.DataValueField = "age"; this.DropDownList5.DataBind();
クラスのListをBind
さらに、自前で作ったクラスにプロパティがあれば、Listコレクションに入っているクラスのプロパティをバインドできる。
//クラスのListをBind var userList = new List<MyUser>(); userList.Add(new MyUser("yamada", 18)); userList.Add(new MyUser("suzuki", 21)); userList.Add(new MyUser("satou", 32)); this.DropDownList4.DataSource = userList; this.DropDownList4.DataTextField = "Name"; this.DropDownList4.DataValueField = "Age"; this.DropDownList4.DataBind();
class MyUser { //自動プロパティ public String Name { get; set; } public int Age { get; set; } public MyUser(String name, int age) { this.Name = name; this.Age = age; } }
例ではC#だが、VB.NETもほぼ同じ。