什么是正确的方式来加载一个列表框? [英] What is the proper way to load up a ListBox?

查看:174
本文介绍了什么是正确的方式来加载一个列表框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是正确的方式来加载一个列表框在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 <​​/ code>,然后用名单,其中,KeyValuePair&GT; 只是为了能够加载这个东西有对象?也许我失去了一些东西明显。我想我的显示文本和值是不同的值。

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.

这篇关于什么是正确的方式来加载一个列表框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆