什么是正确的方式来加载一个列表框
在C#.NET 2.0的WinForms?
What is the proper way to load a ListBox
in C# .NET 2.0 Winforms?
我想我可能只是将其绑定到数据表
。没有这样的运气。
我以为我可以用词典
绑定。没有运气。
I thought I could just bind it to a DataTable
. No such luck.
I thought I could bind it with a Dictionary
. No luck.
我是否需要写一个类名为 KeyValuePair ,然后用
名单,其中,KeyValuePair>
只是为了能够加载这个东西有对象?也许我失去了一些东西明显。我想我的显示文本和值是不同的值。
Do I have to write an class called KeyValuePair
, and then use List<KeyValuePair>
just to be able to load this thing with objects? Maybe I am missing something obvious. I want my display text and values to be different values.
简单code例子。假设你有3个属性一个Person类。名字,姓氏和年龄。说你想你的列表框绑定到Person对象的集合。你想显示显示名字,但价值是年龄。下面是你将如何做到这一点:
Simple code example. Say you have a Person class with 3 properties. FirstName, LastName and Age. Say you want to bind your listbox to a collection of Person objects. You want the display to show the First name, but the value to be the age. Here's how you would do it:
List<Person> people = new List<Person>();
people.Add(new Person { Age = 25, FirstName = "Alex", LastName = "Johnson" });
people.Add(new Person { Age = 23, FirstName = "Jack", LastName = "Jones" });
people.Add(new Person { Age = 35, FirstName = "Mike", LastName = "Williams" });
people.Add(new Person { Age = 25, FirstName = "Gill", LastName = "JAckson" });
this.listBox1.DataSource = people;
this.listBox1.DisplayMember = "FirstName";
this.listBox1.ValueMember = "Age";
诀窍就是将DisplayMember和ValueMember。
The trick is the DisplayMember, and the ValueMember.