Csharp/C#教程:WinForm中comboBox控件数据绑定实现方法分享

本文实例讲述了WinForm中comboBox控件数据绑定实现方法。分享给大家供大家参考,具体如下:

下面介绍三种对comboBox绑定的方式,分别是泛型中IList和Dictionary,还有数据集DataTable

 一、IList

现在我们直接创建一个List集合,然后绑定

IList<string>list=newList<string>(); list.Add("111111"); list.Add("222222"); list.Add("333333"); list.Add("444444"); comboBox1.DataSource=list;

执行后,我们会发现绑定成功,但是我们知道一般对于下拉框的绑定都会有一个值,一个显示的内容,这个时候我们可以创建一个类,把value和text都封装到这个类,作为list的类型

publicclassInfo { publicstringId{get;set;} publicstringName{get;set;} } privatevoidbindCbox() { IList<Info>infoList=newList<Info>(); Infoinfo1=newInfo(){Id="1",Name="张三"}; Infoinfo2=newInfo(){Id="2",Name="李四"}; Infoinfo3=newInfo(){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=newDictionary<int,string>(); kvDictonary.Add(1,"11111"); kvDictonary.Add(2,"22222"); kvDictonary.Add(3,"333333"); BindingSourcebs=newBindingSource(); bs.DataSource=kvDictonary; comboBox1.DataSource=bs; comboBox1.ValueMember="Key"; comboBox1.DisplayMember="Value";

三、数据集

这个比较常见,很简单

//数据集绑定 privatevoidBindCombox() { DataTabledt=newDataTable(); DataColumndc1=newDataColumn("id"); DataColumndc2=newDataColumn("name"); dt.Columns.Add(dc1); dt.Columns.Add(dc2); DataRowdr1=dt.NewRow(); dr1["id"]="1"; dr1["name"]="aaaaaa"; DataRowdr2=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

privatevoidcomboBox1_SelectedIndexChanged(objectsender,EventArgse) { if(this.fig) { stringselectValue=this.cmbAddMember.SelectedValue.ToString(); rtbaddMember.SelectedText=selectValue; } }

那么肯定想在加载窗体后,执行了,所以在加载窗体后我们还要把fig的值设为true

privatevoidSetAutoMessage_Load(objectsender,EventArgse) { loadCombox(); loadMessageTemplet(); fig=true; }

更多关于C#相关内容感兴趣的读者可查看本站专题:《WinForm控件用法上述就是C#学习教程:WinForm中comboBox控件数据绑定实现方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/907841.html

(0)
上一篇 2021年10月25日
下一篇 2021年10月25日

精彩推荐