tags:

views:

86

answers:

4

Hello, I'm .net newbie starting one project for fun. I'm using list box filled with some city names so user can pick one. Every city class has name and UID. How do I know which city user clicked on? Obviously, I can get text of selected item, run through city list and find one by name but that seems stupid.

Is there equivalent to MFC SetItemDataPtr type of thing or what is the most common way of doing it?

A: 

you can get the item selected by user by following code:

list1.SelectedItem;

//text -> list1.SelectedItem.Text
//value-> list1.SelectedItem.Value
TheVillageIdiot
+3  A: 

Assuming that you are referring to a WinForms ListBox, this can be done in the following way.

Instead of setting the Items of the ListBox to an array/collection of strings (as I presume you are currently doing), you could rather set it to an collection of a user-defined type (City in your case), and then use the DisplayMember property (set to Name or whatever the property of your City class that you want to display), so that each item in the ListBox can actually be accessed as the user-defined City object, while it is still displayed by its Name property.

Noldorin
That's exactly what I was looking for. Thanks!
TheBlack
A: 

You can feed the ListBox with an own-defined type of an item, since it accepts an Object, preferably implementing a ToString() method. It can be an object with ID and Name properties so they can be accessed with ListBox's SelectedItem property.

macbirdie
+1  A: 

I would use a ListView (in details mode) instead of a ListBox. Then you could use the Tag property of ListViewItem which is the equivalent of MFC's SetItemDataPtr.

NascarEd
I was just searching for this :) Thank you!
TheBlack