C#ComboBox绑定List

ComboBox绑定List时可能会错,

public class Person
{

public string Name;
public int Age;
public int Heigth;

}

调用如下

List<Person> persons = new List<Person>();
persons.Add(new Person() {Age =12,Name = "asd",Heigth = 123});
persons.Add(new Person() {Age = 20, Name = "YeXinYv", Heigth = 170 });
persons.Add(new Person() {Age = 18, Name = "WuMiao", Heigth = 175 });
comboBox1.DataSource = persons;
comboBox1.DisplayMember = "Age";
comboBox1.ValueMember = "Name";

但是在运行的时候会出错:

至于是什么原因现在我也说不通,不过在我不断的尝试下发现只要给Person的字段加上get就可以解决,如下

public class Person
{
//要是用的字段都必须有 get 没有出错
public Person(int heigth, string name, int age)
{
Heigth = heigth;
Name = name;
Age = age;
}
public string Name { get; }
public int Age { get; }
public int Heigth;
}

调用如下

BindingSource bsSource = new BindingSource();
List<Person> persons = new List<Person>();
persons.Add(new Person(12,"asda",466));
persons.Add(new Person(1122,"aserwda",412366));
persons.Add(new Person(1223,"asdqwa",421366));
comboBox1.DataSource = persons;
comboBox1.DisplayMember = "Age";
comboBox1.ValueMember = "Name";

 

posted @ 2018-07-05 15:09  小男孩的Code  阅读(1370)  评论(0编辑  收藏  举报