I have a list box that displays a set of filenames that reference text files. I think it is aesthetically unappealing to display full paths, so I used Path.GetFileName to cut off the directory part.
But now when the user selects a particular filename to open, I’ve lost the paths. The files could be located anywhere on the local computer (for now).
How can I use the list box so that I can display nice filenames, but also have reference to the actual file?
EDIT: I like the idea of having a custom wrapper class for each list box item.
What’s I’ve done in the past is create a wrapper class for the objects I want to display in the ListBox. In this class override
ToStringto the string you want to display in the ListBox.When you need to get details of a selected item, cast it to the wrapper class and pull the data you need.
Here’s an ugly example:
Fill your ListBox with FileListBoxItems:
Get back the full name of a selected file like this:
Edit
@user1154664 raises a good point in a comment to your original question: how would a user differentiate two ListBox items if the displayed file names are the same?
Here are two options:
Also display each FileListBoxItem’s parent directory
To do this change the
ToStringoverride to this:Display a FileListBoxItem’s full path in a tooltip
To do this drop a ToolTip component on your form and add a
MouseMoveevent handler for your ListBox to retrieve theFileFullnameproperty value of theFileLIstBoxItemthe user is hovering the mouse over.Of course you can use this second option with the first.
Source for the ToolTip in a ListBox (the accepted answer, code reformatted to a flavor I prefer).