After clarification, it's more or less simple.
Here is the technique to use:
You can better use the
ListBox
and populate it with your objects. Now, attention: not with the names of your objects, but with the instances of the objects of your classes themselves. This control allows objects of any types to be added as list items. In this way, each list item will carry complete set of data to be used when the user clicks on the item, selects if or whatever else. Now, the only problem is: what text will be shown as the text of list item? The answer is simple: whatever
ToString
returns. So, you should modify all your classes to be used in this list: properly override
System.Object.ToString()
. Let's see:
class MyListItemData {
internal MyListItemData(string name, string description ) {
this.fName = name;
this.fDescription = description;
}
internal string Name { get { return fName; } }
internal string Description { get { return fDescription; } }
public override string ToString() { return fName; }
string fName, fDescription;
}
Good. Now let's see how it can be used in event handlers. For example, let's implement simple functionality: showing description of each item in selection.
myListBox.SelectedIndexChanged += (sender, eventArgs) => {
ListBox listBox = (ListBox)sender;
int selected = listBox.SelectedIndex;
if (selected < 0)
ShowSelectedItemDescription(null);
else {
MyListItemData data = (MyListItemData)(listBox.Items[selected]);
ShowSelectedItemDescription(data);
}
}
void ShowSelectedItemDescription(MyListItemData data) {
string value;
if (data == null)
value = string.Empty;
else
value = data.Description;
myLabel.Text = value;
}
You can process any other list box events in this manner. An important thing is: you extract the data associated with the item. One hint: you can do more: you can do some action based on the item content. For this purpose, you can include some delegate instances in your class used to add as the list item.
—SA