c# combobox 绑定数据

2025-03-30 06:17:57

1、自定义类型集合数据的绑定 /// <summary> /// 班尽谮惋脑级信息 /// </summary> public class ClassInfo { public int ID { set; get; } public string Name { set; get; } } private void bindClass() { List<ClassInfo> list = new List<ClassInfo>(); for (int i = 1; i <= 10; i++) { ClassInfo classInfo = new ClassInfo() { ID = i, Name = "班级" + i }; list.Add(classInfo); } comboBox1.Items.Clear(); comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; comboBox1.DataSource = list; comboBox1.ValueMember = "ID"; comboBox1.DisplayMember = "Name"; comboBox1.SelectedIndex = 0; }

2、绑定List<T>泛型集合中的数据 private void bindList() { IList<string> list = new List<string>(); list.Add("班级1"); list.Add("班级2"); list.Add("班级3"); list.Add("班级4"); comboBox1.DataSource = list; }

3、Dictionary类型数据的绑定 private void bindDictionary() { Dictionary<int, string> dic = new Dictionary<int, string>(); dic.Add(1, "班级1"); dic.Add(2, "班级2"); dic.Add(3, "班级3"); BindingSource bs = new BindingSource(); bs.DataSource = dic; comboBox1.DataSource = bs; comboBox1.ValueMember = "Key"; comboBox1.DisplayMember = "Value"; }

4、DataTable数据绑定 private void bindDataTable() { DataTable dt = new DataTable(); DataColumn dcID = new DataColumn("ID", Type.GetType("System.Int32")); dt.Columns.Add(dcID); DataColumn dcName = new DataColumn("Name", Type.GetType("System.String")); dt.Columns.Add(dcName); for (int i = 1; i <= 10; i++) { DataRow dr = dt.NewRow(); dr["ID"] = i; dr["Name"] = "班级" + i; dt.Rows.Add(dr); } comboBox1.DataSource = dt; comboBox1.ValueMember = "ID"; comboBox1.DisplayMember = "Name"; }

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢