c# combobox 绑定数据

 时间:2026-02-13 22:34:27

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";

        }

  • 怎么配置标准的ACL(访问控制列表)
  • Windows11如何使用CMD打开客户端网络实用程序
  • 怎样安装uos服务器版本
  • win10电脑在平衡模式下怎么设置休眠时间?
  • 错误137(net::ERR_NAME_RESOLUTION_FAILED):
  • 热门搜索
    sexy是什么意思 机顶盒是什么 妊娠纹是什么 晨字五行属什么 市场专员是做什么的 痔疮有什么症状 ba是什么意思 fbi是什么 g是什么单位 做市商是什么意思