ComboBox 自定义绑定解决方法(WinForm)

以前一直从B/S项目开发,近期在做WinForm项目
虽然出自同祖,但还是有些小问题搞不太明白!
昨天被ComboBox的绑定困扰N久,查询之后,方可解决
现将解决方法记录下来,备用。

1.用ComboBox绑定到数据源,应该来说比较简单:
设置DataSource至对应数据源,设置DisplayName对应到显示字段,搞定。
2.在自定义数据绑定的时候,就出现一点问题
分析问题的本质,应当是对ComboBox的绑定机理理解不够深所至,加至为以前使用过的控件困饶所至
下面是解决办法:
 1public static IList GetBind()
 2{
 3            List<EntityClass> ila = new List<EntityClass>(3);
 4            EntityClass dec = new EntityClass();
 5            dec.Name = "N";
 6            dec.Value = "N";
 7            ila.Add(dec);
 8            dec = new DEClassified();
 9            dec.Name = "W";
10            dec.Value = "W";
11            ila.Add(dec);
12            dec = new DEClassified();
13            dec.Name = "L";
14            dec.Value = "L";
15            ila.Add(dec);
                   return ila;
16}
通过上面的方法获取绑定数据源,然后通过下面绑定代码绑定即可
1System.Collections.IList il = CommonMethod.GetBind();
2this.cb1.DataSource = il;
3this.cb1.DisplayMember = "Name";
4this.cb1.ValueMember = "Value";
5this.cb1.SelectedIndex = 0;

注意在上面代码中,this.cb1.ValueMember必须设置值,为在保存时,读取的项,但在使用数据源绑定时就不必!

参考:
http://www.window07.com/dev/web/net/2006-2-28/k38279.htm
http://www.cnblogs.com/rick/archive/2006/07/11/cmbselidx.html

posted on 2006-10-12 11:22  林子  阅读(4411)  评论(0编辑  收藏  举报

导航