Freitag, 14. Dezember 2007

Windows Forms Controls "Tag" is your best friend

Nearly every Default Windows Forms Control and everything derived from UserControl has it: a property namend Tag.

What is Tag?

The answer is nothing more than just a simple - normally empty - object. Because of it emptiness you could easiely use it for storing data in it. A simple way is just putting easy things in it like numbers or strings. But since Tag is an object you can put any kind of type in it. This could you use in a very helpful way.

Taking an example: If you are programming a Browser. What is with Favourites? Every Browser has such  functionalities. First you have to read your storage's Favourites, after that you maybe want to show the Favourites in a System.Windows.Forms.ToolstripMenu  or even in an ListView or tree view. But how to cope with the clicks? You do not want to display the URL in de menu, you just put it in the Tag. Every added MenuItem (, ListviewItem or TreeViewNode) uses the same method as every other added ManuItem (, ListviewItem or TreeViewNode). You define a string variable named 'URL' and this Variable gets the value from your sender (Before doing this you have to convert sender from an object to your Controltype). After that you just make "URL = Control.Tag" and then you can navigate to this URL. Sure this is just an easy example of using the Tag property but  your clearly see, that Tag is a very useful property for dynamic GUIs.

With this great property you have the abilities to store nearly everything you need for working with the control in the control it self. So you are able to reduce Code for dozens of Click-methods.

Keine Kommentare: