Click here to Skip to main content
15,885,757 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

How to apply many Tags for a Control using C#

Rate me:
Please Sign up or sign in to vote.
4.97/5 (17 votes)
6 May 2012CPOL3 min read 58.9K   13   18
Tag is a useful property, but when you need more than a Tag, what will you plan for it?

Introduction

"A common use for the Tag property is to store data that is closely associated with the control" (MSDN)

Tag is a useful property that few don't use it in their application. For example:

C#
var people = People.Where(p => p.ID == 12);
if(people.Count() > 0)
{
   Person person = people.First();
   FullNameTextBox.Text = person.FullName;
   MyTextBox.Tag = person;
}

But, when you need more than a Tag, what will you plan for it?

Background

One day, my colleague who was exasperated with his task, asked me if there was another junky property except Tag for ComboBox?... Of course we both laughed after a second because Tag was not junky.

Finally, I suggested a solution and I like to share it with you.

Using the code

The solution is very simple, because the data type of Tag is object. It means you can box any type of objects and instances into Tag, among string, int, long, List, Control, and etc.

OK, let's look at this class:

C#
public class ExTag
{
   public Dictionary<string, object> TagDictionary {get; set;}

   public ExTag()//Cunstractor
   {
      this.TagDictionary = new Dictionary<string, object>();
   }

   public void Add(string key , object value)
   {
      this.TagDictionary.Add(key , value);
   }

   public object Get(string key)
   {
      return this.TagDictionary[key];
   }
}

Now, we want to apply two Tags to FullNameTextBox:

C#
ExTag exTag = new ExTag();
exTag.Add("Instance", person);//person is an example. Imagine it's an instance of Person class
exTag.Add("PrevoiusControl", SurnameTextBox);
this.FullNameTextBox.Tag = exTag;

And you know, how to get the values of the tag:

C#
ExTag exTag = (ExTag)(this.FullNameTextBox.Tag);
Person person = (Person)(exTag.Get("Instance"));
TextBox previousControl = (TextBox)(exTag.Get("PrevoiusControl"));

The beauty of this solution is you can categorize your Tags by key names; and the weakness is possibility of your mistaking while naming the keys.

Some Objections and Suggestions

Why not using the Dictionary<string, object> Directly?

I was doing it in the prime of using the solution. In this case, you need to cast the tag to Dictionary<string,> often times. It causes prolonging coding when you are getting the tag. But in my solution you create a class just one time. Please compare Them.

Without ExTag

C#
Person person = (Person)(((Dictionary<string, object>)(this.FullNameTextBox.Tag))["Instance")]);
TextBox previousControl  = (TextBox)(((Dictionary<string, object>)(this.FullNameTextBox.Tag))["Instance")]);

ExTag

C#
ExTag exTag = (ExTag)(this.FullNameTextBox.Tag);
Person person = (Person)(exTag.Get("Instance"));
TextBox previousControl = (TextBox)(exTag.Get("PrevoiusControl"));

Which one looks like it has written by a real programmer?

But Dictionary has more features?!

TagDictionary is a public property and developers are still able to use it's features directly.

Why don't using alias?

Then We have to have alias on the top of all coding assemblies. It's ok but:
It will be a free for all developers (that's the main problem) and the proboblity of mistaking. Look:

C#
using ExTag = Dictionary<string,object>;//First assembly
...
using Alternative = Dictionary<string,object>;//Second assembly. Please Pay attention to name
...
using ExTag = Dictionary<object,object>;//Pay attention to Types object and abject


But if you use ExTag class:
Then we have to create a new instance before defining the tag.And that is all!
But:

C#
RexTag sdsHHdsd = new RegTag();//First using
//...
RegTag alternative = new RegTag();//Second using


1. What is happening after a few months, At least we will easily understand that they are ExTag and they are for Taging! But recognition the intention of a bare dictionary is not as easy as a class.

ExTag Class: "sdsHHdsd"? What a bad name?! but... it's ExTag, I know this type. All team are using this type. Ok let's fixing the name.

using alias: "alternative", let's see what alternative is?! It's a HashTable. Ok, but what is it for?! Where is my coffee?! Ok, Let's trace the code. Aha! It's set as Tag. Hurrah! I got it!

2. For extending its features, a class is more susceptible to be deployed and extended by despiting encapsulation.
3. If you want to change the type of key or value for example you decide to use int instead of string; you can sipmly change the property of the ExTag and all side effects will appear and ready to fix.

Ok, you can use this "public class Extag:Dictionary...", can't you?

Not a bad idea. Of course if we want to extent the class then my idea will seen a little better; but yes, it can also be:

C#
public class ExTag:Dictionary<string,object>
{
   //...
}

Good Luck.

License

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


Written By
Software Developer (Senior)
Iran (Islamic Republic of) Iran (Islamic Republic of)
Microsoft Certified Technology Specialist (MCTS)


"شاهین خورشیدنیا"


Nobody is perfect and neither am I, but I am trying to be more professional. In my humble opinion, you have to develop your skills, as long as you are responsible for developing even a tiny part of a sustainable software. That makes this job so special to me.

Comments and Discussions

 
GeneralMy vote of 5 Pin
poevin12-Apr-20 3:20
poevin12-Apr-20 3:20 
GeneralMy vote of 5 Pin
Franc Morales14-Oct-18 15:56
Franc Morales14-Oct-18 15:56 
SuggestionNice Pin
Lorenzo.924-Dec-14 7:16
Lorenzo.924-Dec-14 7:16 
SuggestionAlternate solution Pin
Bekjong18-Mar-13 19:42
Bekjong18-Mar-13 19:42 
GeneralRe: Alternate solution Pin
Shahin Khorshidnia18-Mar-13 22:52
professionalShahin Khorshidnia18-Mar-13 22:52 
GeneralMy vote of 5 Pin
Mohammad A Rahman26-May-12 15:37
Mohammad A Rahman26-May-12 15:37 
GeneralRe: My vote of 5 Pin
Shahin Khorshidnia26-May-12 18:04
professionalShahin Khorshidnia26-May-12 18:04 
Questionhello Pin
jeta5457-May-12 5:12
jeta5457-May-12 5:12 
AnswerRe: hello Pin
Shahin Khorshidnia7-May-12 5:56
professionalShahin Khorshidnia7-May-12 5:56 
QuestionYou don't need to create a new class to keep code clean Pin
Matt T Heffron1-May-12 10:54
professionalMatt T Heffron1-May-12 10:54 
GeneralRe: You don't need to create a new class to keep code clean Pin
PIEBALDconsult1-May-12 11:31
mvePIEBALDconsult1-May-12 11:31 
GeneralRe: You don't need to create a new class to keep code clean Pin
Shahin Khorshidnia1-May-12 11:42
professionalShahin Khorshidnia1-May-12 11:42 
GeneralRe: You don't need to create a new class to keep code clean Pin
FerretallicA1-May-12 14:13
FerretallicA1-May-12 14:13 
GeneralRe: You don't need to create a new class to keep code clean Pin
PIEBALDconsult1-May-12 14:48
mvePIEBALDconsult1-May-12 14:48 
GeneralRe: You don't need to create a new class to keep code clean Pin
Ankush Bansal20-May-12 18:42
Ankush Bansal20-May-12 18:42 
GeneralThank you Pin
Shahin Khorshidnia2-May-12 1:22
professionalShahin Khorshidnia2-May-12 1:22 
GeneralRe: Thank you Pin
PIEBALDconsult2-May-12 8:24
mvePIEBALDconsult2-May-12 8:24 
GeneralRe: Thank you Pin
Shahin Khorshidnia2-May-12 11:25
professionalShahin Khorshidnia2-May-12 11:25 

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.