Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Gaining Control of the .NET ListBox : Page 4

Although .NET's Windows Forms ListBox control has extended capabilities, it can be problematic to do some of the simplest things. But by using delegates, you can achieve near-total control.


advertisement
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) _ Handles Button4.Click 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 _ DisplayPersonStatus) ' display the results ListBox1.DataSource = Nothing ListBox1.DataSource = people End Sub

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 array—and 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.



A. Russell Jones is the Executive Editor of DevX.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date