3

In a .NET treeview you can create nodes, subnodes and elements. All I seem to be able to do is give them names.

But how can I attach information (any object) to an element?

1 Answers1

3

Use the Tag property of the TreeNode to attach an arbitrary object to it.

This doesn't affect the TreeView in any way. It is especially useful in your event handlers, (e.g. AfterSelect) because allows you to refer back to one of "your" objects from the TreeNode that is referenced.

Remember that Tag is of type Object, so you'll want to be careful how you access it. Here's some sample code to show how (I feel) it is best used:

public Form1()
{
    InitializeComponent();
    theTree.AfterSelect += (sender, args) => ShowSelectedNode();
}

private void ShowSelectedNode() {
    var node = theTree.SelectedNode;

    var viewable = node.Tag as IViewable;
    if (viewable != null) {
        viewable.View(this);
    }
}

Note that this is the correct use of the as operator.

Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • Wow that was fast. And you caught me not having read the docs properly. Sorry - and Thanks! – user3599802 May 03 '14 at 18:58
  • @user3599802 Not a problem. Some .NET classes like these have *lots* of properties and events, and it can be hard to figure out just which one you want to use. I've added some sample code from one of my projects, where the nodes may actually have different types of nodes attached to them. In this case, using an `interface` really cleans up the "on click" logic. – Jonathon Reinhart May 03 '14 at 19:05