Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top