Who Needs ItemData?
This solution accomplishes one other thing that, until now, was impossible without writing customized code: You can set a different DisplayMethod
for each instance
of a class. The Custom button illustrates this capability by setting the Status property of the "Jane Austen" Person object to a custom string.
Private Sub Button4_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Dim p As Person
' retrieve Jane Austen
p = CType(people(1), Person)
' set a custom Status string
p.Status = "Not at home. Whew!"
' change only this Person objects' DisplayMethod
p.DisplayMethod = New Person. _
displayPersonDelegate (AddressOf _
' display the results
ListBox1.DataSource = Nothing
ListBox1.DataSource = people
When you click the button, the results look like Figure 5
Finally, giving class consumers the ability to create customized display strings for your classes goes a long way toward making the missing ItemData
truly unnecessary. When you click on an item in the ListBox, it displays a MessageBox that shows the selected item and its ID
, proving that associating an ID
with an item by using objects works just as well as the older ItemData
arrayand doesn't require the class consumer to write any code.
One small downside of this method is that if you want to post two ListBoxes side by side, both containing the same objects, but one displaying (for example) LastName/FirstName and the other displaying FirstName/LastName, you need to implement a Clone
method so you can set different display methods for the objects in each list. In this particular case, writing a wrapper object to handle the class display may be a better design.