Item data in ListBox (Windows Forms)

How can I keep item data associated with ListBox item?
I expected to have the Tag property, but ListBox.ObjectCollection contains Object members.
LVL 48
AlexFMAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
SRigneyConnect With a Mentor Commented:
The good thing about a ListBox is that you can add objects and tell it what to display.  Then any additional properties that you want are already associated with the record, you just need to cast it when you get it out.

For example, let's say I have a class, clsMyItem, the ToString has been overriden  with the data I want displayed.

I can Add the object to the listbox, and when I want to get it out I just do
clsMyItem CurrentItem = (clsMyItem)ListBox1.SelectedItem

Now I have access to all of the properties that were on the original object that was added.  Which is what is usually really wanted with the ItemData property anyway.
0
 
AlexFMAuthor Commented:
For example, ListView.ListViewItemCollection Class contains ListViewItem members, and I can use ListViewItem.Tag Property to keep data associated with ListView item. What can I do with ListBox?
0
 
EBatistaCommented:
use the pair DisplayMember and ValueMember properties instead.
ie. if this is a database app you could store in the ValueMember the primary key of a table and in DisplayMember the text that users see in the control:

ListBox1.DataSource=tableUsers
ListBox1.DisplayMember="UserName"
ListBox1.ValueMember="UserID"

then to retrieve the primary key value corresponding to the selected item you can use the SelectedValue property:

string strKey=ListBox1.SelectdValue.ToString()

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.