WinForm控件之ComboBox控件使用

ComboBox控件的两种添加数据方式

  1. 手动添加
    手动添加可以通过代码的形式添加,也可以在属性Items中添加
  • 通过代码手动添加项
点击查看代码
private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("1");
            comboBox1.Items.Add("2");
            comboBox1.Items.Add("3");
            comboBox1.Items.Add("4");
            comboBox1.Items.Add("5");
        }
* 在属性Items中添加项 ![](https://img2022.cnblogs.com/blog/1594407/202203/1594407-20220312160833616-1208431004.png) 两者得到的结果是一样的: ![](https://img2022.cnblogs.com/blog/1594407/202203/1594407-20220312160920423-1204960984.png)
  1. 绑定数据源
    可以绑定List、DataTable等数据源
  • 绑定List
点击查看代码
private void Form1_Load(object sender, EventArgs e)
        {
            List<DataItem> listDataItem = new List<DataItem>();
            listDataItem.Add(new DataItem { code = "1", name = "北京" });
            listDataItem.Add(new DataItem { code = "2", name = "上海" });
            listDataItem.Add(new DataItem { code = "3", name = "广州" });
            listDataItem.Add(new DataItem { code = "4", name = "深圳" });

            comboBox1.DataSource = listDataItem;
            comboBox1.DisplayMember = "name";
            comboBox1.ValueMember = "code";
        }
* 绑定DataTable
点击查看代码
private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("code");
            dt.Columns.Add("name");

            DataRow dr1 = dt.NewRow();
            dr1["code"] = "1";
            dr1["name"] = "北京";
            dt.Rows.Add(dr1);

            DataRow dr2 = dt.NewRow();
            dr2["code"] = "2";
            dr2["name"] = "上海";
            dt.Rows.Add(dr2);

            DataRow dr3 = dt.NewRow();
            dr3["code"] = "3";
            dr3["name"] = "广州";
            dt.Rows.Add(dr3);

            DataRow dr4 = dt.NewRow();
            dr4["code"] = "4";
            dr4["name"] = "深圳";
            dt.Rows.Add(dr4);

            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "name";
            comboBox1.ValueMember = "code";
        }

注意:ComboBox的手动绑定方式和绑定数据源方式不能混用!

posted @ 2022-03-12 16:43  Meltykiss11  阅读(665)  评论(0编辑  收藏  举报