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";
The trick is the DisplayMember
, and the ValueMember
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…