(winform)对于ComboBox控件的使用

ComboBox控件添加显示和数值分开数据时有两种方式:

1,自定义一个数据结构,创建自定义结构对象后使用comboBox.Add(自定义对象)方法添加,再分别指定其DisplayMember和ValueMember。这种方法要获取被选中的数值,不能使用SelectedValue属性(因为获取的将是null),需要使用((自定义对象类型)comboBox1.SelectedItem).Value来取得当前选择的值。
2,另一种方法是combBox.DataSource来指定的ComboBox的数据源(IList<自定义对象类型或KeyValuePair>或者DataTable),然后指定DisplayMember和ValueMember,此时即可以通过SelectedValue获取被选中的值,也可动态设置SelectedValue属性来显示指定值所对应的显示内容(这有个前提,必须要先设置好ComboBox控件的父窗体,如下代码)。

            ComboBox comboBoxCarPlateColor = new ComboBox();
            var listCarPlateColor = new List<KeyValuePair<string, string>>();
            listCarPlateColor.Add(new KeyValuePair<string, string>("1", "蓝色"));
            listCarPlateColor.Add(new KeyValuePair<string, string>("2", "黄色"));
            listCarPlateColor.Add(new KeyValuePair<string, string>("3", "黑色"));
            listCarPlateColor.Add(new KeyValuePair<string, string>("4", "白色"));
            listCarPlateColor.Add(new KeyValuePair<string, string>("5", "其它"));
            comboBoxCarPlateColor.DataSource = listCarPlateColor;
            comboBoxCarPlateColor.ValueMember = "key";
            comboBoxCarPlateColor.DisplayMember = "value";
            comboBoxCarPlateColor.Parent = this;//加入这一句
            comboBoxCarPlateColor.SelectedValue = "2";
            this.Controls.Add(comboBoxCarPlateColor);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值