2008-11-19 251 views
22

什么是在C#.NET 2.0 Winforms中加载ListBox的正确方法?什么是加载列表框的正确方法?

我想我可以将它绑定到DataTable。没有这样的运气。
我想我可以将它与Dictionary绑定。没有运气。

我必须编写一个名为KeyValuePair的类,然后使用List<KeyValuePair>只是为了能够用对象加载这个东西?也许我错过了一些明显的东西。我想让我的显示文字和数值成为不同的值。

回答

59

简单的代码示例。假设你有一个Person类有3个属性。 FirstNameLastNameAge。假设你想将你的列表框绑定到一个Person对象的集合。您希望显示器显示名字,但值是年龄。这里是你会怎么做:

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

诀窍是DisplayMemberValueMember

5

让我们假设你的数据类型被称为MyDataType。在该数据类型上实现ToString()以确定显示文本。例如:

class MyDataType 
{ 
    public string ToString() 
    { 
    //return the text you want to display 
    } 
} 

然后你可以采取列表,包括你的数据类型,并通过的AddRange它塞进列表框()如下:

ListBox l; 
List<MyDataType> myItems = new List<MyDataType>(); // populate this however you like 
l.AddRange(myItems.ToArray()); 

让我知道如果你需要更多的帮助 - 这将有助于了解您试图在列表框中显示的数据类型。

+0

我想这似乎很奇怪。如果您正在使用一个小型项目,而您正在使用DataSets/DataTables并且没有业务对象。我想我可能只是写一个KeyValuePair类。 公共类KeyValuePair { 公共对象键{获得;设置;} 公共对象值{获取;集;}} 时 – BuddyJoe 2008-11-19 20:52:01

+0

没有,我想念他们加入了内置KVP的框架......哎呀,我觉得哑。 – BuddyJoe 2008-11-19 20:56:05

3

您可以将数据源设置为您喜欢的实现IList或IListSource的任何数据源。

您还需要将DisplayMember和ValueMember属性设置为您要显示的字段并分别具有相关的值。

5

你可以直接bind a DataTable ...

listbox.ValueMember = "your_id_field"; 
listbox.DisplayMember = "your_display_field"; 
listbox.DataSource = dataTable; 
1

使用paramater用于明智吸性能的数据源 - 上组合框至少,

我现在很大程度上适应了对象上覆盖的ToString()就像上面描述的另一位评论者那样使用Items.AddRange()方法添加对象。

1

要绑定到一个字典,你必须把它包装在一个新的BindingSource对象中。

MyListBox.DataSource = New BindingSource(Dict, Nothing) 
MyListBox.DisplayMember = "Value" 
MyListBox.ValueMember = "Key" 
相关问题