List添加自定义类 给Combox(下拉框)绑定某个字段值

首先定义数据类:

public class Student
    {
        public int ID {set;get;}//注意这里必须是属性的形式,否则绑定的时候无法用属性名来绑定
        public string StuName {set ;get;}
    }

然后是调用:

List<Student> stu = new List<Student>();
            Student stu1 = new Student();
            stu1.ID = 1;
            stu1.StuName = "米克";
            stu.Add(stu1);
            stu1.ID = 2;
            stu1.StuName = "寒梅";
            stu.Add(stu1);
            comboBox1.DataSource = stu;
            comboBox1.DisplayMember = "StuName";
            comboBox1.ValueMember = "ID";

如果类中的属性这样定义的(将无法绑定到具体的值):

public class Student
    {
        public int ID =0;
        public string StuName="";//这声明的是字段 而非“属性”
    }

其实和数据绑定控件的绑定原理有关:参考clingingboy控件开发系列:http://www.cnblogs.com/Clingingboy/archive/2007/02/11/647402.html

PropertyDescriptor 绑定时获取公开属性

Student ss = new Student();
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(ss);

            // Sets an PropertyDescriptor to the specific property.
            System.ComponentModel.PropertyDescriptor myProperty = properties.Find("StuName", false);
            string nihao = "";
            // Prints the property and the property description.
            if (myProperty != null)//修改定义类的 属性 和 字段,来判断是否跟这个定义有关
            {
                nihao = myProperty.DisplayName + '\n';
                nihao += myProperty.Description + '\n';
                nihao += myProperty.Category + '\n';
            }


 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值