Click here to Skip to main content
16,006,348 members
Articles / Programming Languages / C#

The miracle of Tag

Rate me:
Please Sign up or sign in to vote.
1.16/5 (13 votes)
17 Jun 2007CPOL 18.3K   8   6
How to use the Tag property.

Introduction

Not a lot of people realize how powerful the Tag property actually is... (For people coming from other languages like Delphi where the Tag property is a String, using the Tag as an Object opens lots of opportunities.)

I will give you a quick overview and show you how you can use it.

Using the code

The Tag property is of type Object, making it a very powerful to work with. An Object is like the seed of OO.

Here is an example of how you can use it:

First, you will need to create a class with all the details you want to save.

C#
public class Person
{
    public string Name;
    public string Surname;
}

Then, you populate it and link it to any Tag property. As easy as that:

C#
// Create an temporary Person object
Person TempPerson = new Person();

// Populate it
TempPerson.Name = "Jack";
TempPerson.Surname = "The-Man!!!";

//Link the Temp object to the Tag
this.Tag = TempPerson;

// Get the Data back from the Tag
this.Text = 
    ((Person)this.Tag).Name + 
    " " +
    ((Person)this.Tag).Surname;

With the above code, I use the the Form (this) and link an object of any kind to the Tag property. Very handy!!!

In your day to day apps, you can use this to save limitless data on any Tag property (create a Node Index for example, and or link all the info you may need to a Tree Node.)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
New Zealand New Zealand
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralNot a very good example Pin
Robert Rohde18-Jun-07 3:07
Robert Rohde18-Jun-07 3:07 
GeneralRe: Not a very good example Pin
Bertus Kruger18-Jun-07 9:47
Bertus Kruger18-Jun-07 9:47 
GeneralRe: Not a very good example [modified] Pin
taras_b19-Jun-07 18:45
taras_b19-Jun-07 18:45 
GeneralRe: Not a very good example Pin
Bertus Kruger19-Jun-07 20:34
Bertus Kruger19-Jun-07 20:34 
Exactly!!!

It keeps it all together without having to extend the standard controls.

Makes life a lot easier.. Smile | :)

QuestionUsage? Pin
andre1234518-Jun-07 1:32
andre1234518-Jun-07 1:32 
AnswerRe: Usage? Pin
Bertus Kruger18-Jun-07 9:50
Bertus Kruger18-Jun-07 9:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.