一、IList
现在我们直接创建一个List集合,然后绑定
IList<string> list = new List<string>(); list.Add("111111"); list.Add("222222"); list.Add("333333"); list.Add("444444"); comboBox1.DataSource = list;
public class Info { public string Id { get; set; } public string Name { get; set; } } private void bindCbox() { IList<Info> infoList = new List<Info>(); Info info1 = new Info() { Id="1",Name="张三"}; Info info2 = new Info() { Id="2",Name="李四"}; Info info3 = new Info() { Id = "3",Name = "王五" }; infoList.Add(info1); infoList.Add(info2); infoList.Add(info3); comboBox1.DataSource = infoList; comboBox1.ValueMember = "Id"; comboBox1.DisplayMember = "Name"; }
二、Dictionary
不能直接绑定,需要借助类BindingSource才可以完成绑定
Dictionary<int, string> kvDictonary = new Dictionary<int, string>(); kvDictonary.Add(1, "11111"); kvDictonary.Add(2, "22222"); kvDictonary.Add(3, "333333"); BindingSource bs = new BindingSource(); bs.DataSource = kvDictonary; comboBox1.DataSource = bs; comboBox1.ValueMember = "Key"; comboBox1.DisplayMember = "Value";
三、数据集
//数据集绑定 private void BindCombox() { DataTable dt = new DataTable(); DataColumn dc1 = new DataColumn("id"); DataColumn dc2 = new DataColumn("name"); dt.Columns.Add(dc1); dt.Columns.Add(dc2); DataRow dr1 = dt.NewRow(); dr1["id"] = "1"; dr1["name"] = "aaaaaa"; DataRow dr2 = dt.NewRow(); dr2["id"] = "2"; dr2["name"] = "bbbbbb"; dt.Rows.Add(dr1); dt.Rows.Add(dr2); comboBox1.DataSource = dt; comboBox1.ValueMember = "id"; comboBox1.DisplayMember = "name"; }
取值:
combox.SelectedValue