Easy object binding to Treeview Node

Are you looking for something like the Tag property on TreeNodes? It can hold any object.

http://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.tag.aspx


imho you have several strategies :

  1. stick an object of any type in the Tag property of any Node : downside : you'll have to cast it back to its 'native form' when you retrieve it to use it : if that "native form" is anything but type 'Object.

  2. sub-class TreeNode, and add a public fields, Public Properties, or whatever, for your objects ... or even List ... ... or whatever you need to associate with the Node.

  3. assuming your objects are of the same type, you could create a dictionary of type : Dictionary <TreeNode, myObjectType>, instantiate it, and, as needed, store a TreeNode and its associated Object(s) that way as a Key/Value Pair.

Strategies #1, and #3 have the advantage that you can store an associated object ONLY as needed Strategy #2 : is more suited to the case where you anticipate every TreeNode is going to have an associated object(s).

Of course with stragies #1 and #3, you will need to test at run-time for the presence or absence of an object associated with a particular Node.

Strategy #1's an easy test : if the Tag propety of the Node is Null : you know there's no object : if not null ... and there may be more than one type of object stored in the Tag field ... then you'll have to pull out the Tag object, and make sure it's the right type as in : (the example that follows assumes a public class, "Class1," has been assigned to tag of the first node in the TreeView :

TreeNode thisNode = theTreeView.Nodes[0];
if (((thisNode.Tag != null) && (thisNode.Tag is Class1))) ... handle the object ...

Strategy #3 is a little easier since you can just evaluate if the Dictionary<Node, myObject>.Contains the Node as a Key.


This MSDN article has some good information, for example:

class myTreeNode : TreeNode
{
   public string FilePath;

   public myTreeNode(string fp)
   {
      FilePath = fp;
      this.Text = fp.Substring(fp.LastIndexOf("\\"));
   }
}

Tags:

C#

Treeview