Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

c# - What is the proper way to load up a ListBox?

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...