C# - ListBox DataSource 属性并绑定一个 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/816710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# - ListBox DataSource property and binding an ArrayList
提问by Mariusz Schimke
I created an ArrayList which contains KeyValuePair<string, string> objects. There are ListBoxes which I would like to bind to that list so that I do not have to fill them by iteration, copying at the same time all the data I have in the above mentioned ArrayList.
我创建了一个包含 KeyValuePair<string, string> 对象的 ArrayList。有一些 ListBoxes 我想绑定到该列表,这样我就不必通过迭代来填充它们,同时复制我在上述 ArrayList 中拥有的所有数据。
I am a Delphi programmer and in Delphi I would use the ListView control, set its OwnerData property to true and then use the OnData event to make a given item (with a specified index) display any piece of data from an array item having the same index. The OnData method gives me the currently displayed item as a parameter so I have access to e.g. its Index, Caption and SubItems properties. Basing on that index I can make the item display some data from an array item having the same index. If that array is modified, it is enough to refresh the ListView and/or set its Count property if the length of the array changed.
我是 Delphi 程序员,在 Delphi 中,我将使用 ListView 控件,将其 OwnerData 属性设置为 true,然后使用 OnData 事件使给定项目(具有指定索引)显示来自具有相同指数。OnData 方法为我提供了当前显示的项目作为参数,因此我可以访问例如它的 Index、Caption 和 SubItems 属性。基于该索引,我可以使该项目显示来自具有相同索引的数组项目的一些数据。如果该数组被修改,则在数组的长度发生变化时刷新 ListView 和/或设置其 Count 属性就足够了。
How to achieve the same goal in C# using the ListBox control? I set the listBox.DataSource property to myArrayList containing KeyValuePairs. Now I would like the listBox to display the keys of the KeyValuePairs objects.
如何使用 ListBox 控件在 C# 中实现相同的目标?我将 listBox.DataSource 属性设置为包含 KeyValuePairs 的 myArrayList。现在我希望 listBox 显示 KeyValuePairs 对象的键。
采纳答案by Tim Robinson
.NET list boxes have this functionality built in. You've already set the DataSource
property, so to display just the keys in the list, set:
.NET 列表框内置了此功能。您已经设置了该DataSource
属性,因此要仅显示列表中的键,请设置:
listBox.DisplayMember = "Key";