Home
C#.WinForms
Tag Property
Updated Sep 25, 2022
Dot Net Perls
Tag. The Tag property stores an object reference. Windows Forms programs can use complex object models. With Tag, we can store objects directly on controls.
Property notes. But the Tag property is a simple way to link a certain object to a certain control. It is useful in certain situations.
This program shows the use of the Tag property inside the object model. The Form1 constructor assigns the Tag property to a new ExampleTag—a custom type.
Then This object reference can be accessed at any time and in any method later in the event loop of the Windows program.
Detail In the Form1 constructor, the ExampleTag constructor is called. A reference is copied to the Tag reference field.
Next In the Form1_Load event handler, we see that you can access the Tag property on the enclosing control.
And This is the same Tag that we previously set. We could also modify the ExampleTag object at this point.
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); // Set tag on constructor. this.Tag = new ExampleTag(1, 2); } private void Form1_Load(object sender, EventArgs e) { // When form loads, render tag to the title bar. this.Text = this.Tag.ToString(); } } class ExampleTag { public int _a; public int _b; public ExampleTag(int a, int b) { // Store the fields. this._a = a; this._b = b; } public override string ToString() { // Write the fields to a string. return string.Format("Tag a = {0}, b = {1}", this._a, this._b); } } }
The window is displayed with the title bar reading the tag ToString output.
Program notes. When you invoke ToString upon a base class, the most derived method is called. You can see that the title bar of the program is equal to the result of the ToString method.
A warning. If we use Tag, we may confuse the user interface specific information in the program with the data model. This could make porting to new interfaces more difficult.
Summary. We explored an example usage of the Tag property. The Tag property essentially provides a user-defined field that can store any form of object in a persistent way.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 25, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen