C#ComboBox绑定List

当尝试将一个包含Person对象的List绑定到C# ComboBox时,如果Person类的属性没有getter,会导致运行时错误。通过为Person类的属性添加getter,可以解决这个问题。示例代码展示了如何正确绑定DataSource、DisplayMember和ValueMember。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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";

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值