views:

5845

answers:

1

Hi.

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.

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.

My question is 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. Could you please help me do that?

Thanks a lot!

Mariusz.

+5  A: 

.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:

listBox.DisplayMember = "Key";
Tim Robinson
Excellent! I'd add "listBox.ValueMember = "Value";" I hate lists without values! ;-)
Cerebrus
You could do that too -- it depends whether you want listBox.SelectedValue to give you a KeyValuePair<string, string> or just a string.
Tim Robinson