ListBox
在C#.NET 2.0 Winforms中加载一个正确的方法是什么?
我以为我可以将它绑定到一个DataTable
.没有这样的运气.
我以为我可以用它绑定它Dictionary
.没运气.
我是否必须编写一个名为的类KeyValuePair
,然后使用List
只是为了能够用对象加载这个东西?也许我错过了一些明显的东西.我希望我的显示文本和值是不同的值.
简单的代码示例.假设您有一个Person
包含3个属性的类.FirstName
,LastName
和Age
.假设您要将列表框绑定到Person
对象集合.您希望显示器显示名字,但值显示为年龄.这是你如何做到的:
Listpeople = new List (); 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
.
您可以直接绑定DataTable ...
listbox.ValueMember = "your_id_field"; listbox.DisplayMember = "your_display_field"; listbox.DataSource = dataTable;
让我们假设您的数据类型称为MyDataType.在该数据类型上实现ToString()以确定显示文本.例如:
class MyDataType { public string ToString() { //return the text you want to display } }
然后,您可以获取由您的数据类型组成的列表,并通过AddRange()将其塞入ListBox,如下所示:
ListBox l; ListmyItems = new List (); // populate this however you like l.AddRange(myItems.ToArray());
如果您需要更多帮助,请告诉我们 - 了解您要在列表框中显示的数据类型会有所帮助.