WinForm中comboBox控件数据绑定实现方法
程序员文章站
2023-11-12 19:24:28
本文实例讲述了winform中combobox控件数据绑定实现方法。分享给大家供大家参考,具体如下:
下面介绍三种对combobox绑定的方式,分别是泛型中ilist和d...
本文实例讲述了winform中combobox控件数据绑定实现方法。分享给大家供大家参考,具体如下:
下面介绍三种对combobox绑定的方式,分别是泛型中ilist和dictionary,还有数据集datatable
一、ilist
现在我们直接创建一个list集合,然后绑定
ilist<string> list = new list<string>(); list.add("111111"); list.add("222222"); list.add("333333"); list.add("444444"); combobox1.datasource = list;
执行后,我们会发现绑定成功,但是 我们知道一般对于下拉框的绑定都会有一个值,一个显示的内容,这个时候我们可以创建一个类,把value和text都封装到这个类,作为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的selectedindexchanged的事件后,我们在加载窗体的时候就会执行,这点我刚开始也和魅惑,导致容易出错,这点我们可以采取一些方法避免执行,比如可以定义一个变量fig=false
private void combobox1_selectedindexchanged(object sender, eventargs e) { if(this.fig) { string selectvalue = this.cmbaddmember.selectedvalue.tostring(); rtbaddmember.selectedtext = selectvalue; } }
那么肯定想在加载窗体后,执行了,所以在加载窗体后我们还要把fig的值设为true
private void setautomessage_load(object sender, eventargs e) { loadcombox(); loadmessagetemplet(); fig= true; }
更多关于c#相关内容感兴趣的读者可查看本站专题:《winform控件用法总结》、《c#窗体操作技巧汇总》、《c#数据结构与算法教程》、《c#常见控件用法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结》
希望本文所述对大家c#程序设计有所帮助。
推荐阅读
-
C#实现ComboBox控件显示出多个数据源属性的方法
-
WinForm中comboBox控件数据绑定实现方法
-
C#实现读取DataSet数据并显示在ListView控件中的方法
-
WinForm 中 comboBox控件之数据绑定
-
AngularJS中ng-options实现下拉列表的数据绑定方法
-
JS中Object.defineProperty()方法实现数据双向绑定
-
C#实现ComboBox控件显示出多个数据源属性的方法
-
Winform开发中如何将数据库字段绑定到ComboBox控件
-
C#实现读取DataSet数据并显示在ListView控件中的方法
-
WinForm 中 comboBox控件之数据绑定