Track an item in a list

I am a .net newbie starting one project for fun. I am using a list filled with city names so the user can choose one. Each city class has a name and a UID. How do I know which city was clicked on? Obviously I can get the text of the selected item, loop through the list of cities and search by name, but that seems silly.

Is there an equivalent to the MFC type SetItemDataPtr or what's the most common way to do this?

+1


a source to share


4 answers


Assuming you are linking to WinForms ListBox

, it can be done like this.



Instead of setting Items

from ListBox

to an array / collection of strings (as I suppose you are doing now), you can rather set it to a set of custom type ( City

in your case) and then use a property DisplayMember

(set to Name

or something like a property of your class City

you want to display) so that each element in ListBox

can actually be accessed as a custom object City

, as long as it is still displayed by its property Name

.

+3


a source


I would use ListView (in verbose mode) instead of ListBox. Then you can use the Tag property of the ListViewItem, which is the MFC equivalent of SetItemDataPtr.



+1


a source


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

list1.SelectedItem;

//text -> list1.SelectedItem.Text
//value-> list1.SelectedItem.Value

      

0


a source


You can combine a ListBox with a specific item type as it accepts Object

, preferably by implementing a method ToString()

. It can be an object with IDs and Name properties so that they can access the ListBox property SelectedItem

.

0


a source







All Articles