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

来源:互联网 发布:ios哪个vpn好用 知乎 编辑:程序博客网 时间:2024/05/22 03:11

首先定义数据类:

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';            } 
原创粉丝点击