Store Objects in a List

Problem

You want to store custom objects in a list, and customize their display.

Solution

You can add custom objects directly to the ListBox.Items collection. However, you must override the ToString method in your custom class to set the text that will appear in the ListBox, or set the ListBox.DisplayMember property.

Discussion

The .NET list controls (the ListBox, ComboBox, and CheckedListBox) can hold any type of object, whether it’s an ordinary string or a custom class or structure that contains several pieces of information. However, if you attempt to store custom classes in a list box, you might discover that the text does not appear correctly. Instead, the fully qualified class name will be shown for each item in the list. ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.