C#ComboBox绑定List

ComboBox绑定List时可能会错,

public class Person
{

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

}

调用如下

List persons = new List();
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";

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

C#ComboBox绑定List_第1张图片

至于是什么原因现在我也说不通,不过在我不断的尝试下发现只要给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 persons = new List();
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";

 

转载于:https://www.cnblogs.com/miaoziblog/p/9268418.html

你可能感兴趣的:(C#ComboBox绑定List)