[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1004
  • Last Modified:

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.
0
AlexFM
Asked:
AlexFM
1 Solution
 
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
 
SRigneyCommented:
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
 
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

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now