I am writing a winforms app in which a user selects an item from a listbox and edits some data that forms part of an associated object. The edits are then applied from the object list to an underlying file.
In ASP.Net assigning a different system value to a list item than the display text the user sees is trivial. In a winforms app you have to set the ‘Displaymember’ and the ‘Valuemember’ of each item in a slightly more complicated (and not oft related on the internet) process.
This I have done. In debug mode I have confirmed that every item now has a value which is the display member (a ‘friendly’ string that the user sees) and a key, the valuemember, which holds the key to a hashtable object where the data to be updated exists.
So when a user picks a string to edit the program should pass the ‘key’ to the hashtable, yank out the object and allow editing to take place upon it.
The catch?
I can’t see any obvious way of telling the program to look at the item’s valuemember. I naively expected it to populate the list box’s ‘SelectedValue’ property, but that would be too simple by far. So how the hell do I get to the list item value?
Okay so the answer came as a result of Andy’s answer, hence my upvoting that answer.
But when I created a little class and tried to cast the listitem into that class the program threw an exception.
Revealingly the exception told me that the program could not cast a DictionaryEntry into a class of the type I had defined.
So I deleted the proxy class and reframed the request thus:
And it’s all good.
Bizarrely simple answer in the end. Thanks for the hint Andy.