C# Winforms and the Hidden Association Tag

There is a little known property off of the Control class called Tag. Since most winform controls derive from this base Control class the Tag property is on most everything that one does with winforms. The tag’s purpose is to associate user data with the control. When building a list or a tree, each node can have a reference to the object that it is associated to. That is very handy when one receives an event and the event gives the node of the tree in question and instead of fishing for the original object in some other list, just one retrieves it off of the Tag property!

For example I created a DataGridView where individual rows had unique columns that needed to reference data that was more than just a boolean or a string. When working with each row’s cell I attached specialized data target objects which needed to be processed when the user sets or edits the value. When I created the row and columns, I would new up a specialized object for each cell and attach then to the row[cell index].Tag. Below we look at two cells. On one cell, I had create a specialized sql object and the other had an XmlDocument to hold the user’s work.

// We have a new row of blank data, create the
// specialized objets for the specific columns
e.Row.Cells[SQLColumn].Tag   = new SQL();
e.Row.Cells[RulesColumn].Tag = new XmlDocument();
// Populating other columns with appropriate data

Then when a user clicks on the SQL cell to edit, I receive this message and allow extract of the specialized object to work on in a winform popup:

private void dataGridViewMain_CellContentClick( object sender, DataGridViewCellEventArgs e )

  DataGridView grid = (DataGridView)sender;

  // Filter out clicks not in the DirectReports column
  if (e.RowIndex >= 0)
      switch (e.ColumnIndex)
      case SQLColumn: // SQL
          SQL editObject = grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag as SQL;
          MySQLEditForm edit = new MySQLEditForm(editObject);

See how handy the tag can be…use it next time. Also get in the habit of creating Tags on objects you create. One never knows what the consumer may use it for, but your consumer will be happy!


Leave a Reply