Jonathan Hilgeman

Everything complex is made up of simpler things.

Hiding TreeNodes in C#


In a recent project, I was building out a TreeView control that could be searched and filtered. One of the primary problems was that there was no proper way to hide a TreeNode temporarily. The solution was fairly simple, though, and performed very well.

1. I started by created a new class that extended the base TreeView class.

2. Inside the new class, I defined a public TreeView called tvHidden, which held the nodes that were temporarily hidden.

3. I then added two public methods, Hide and Show, which both accepted a TreeNode as a parameter.

4. In the Hide method, I used the TreeNode’s Tag to store a reference to the original parent (Node.Parent), then removed the node from its current collection and added it to the tvHidden Nodes collection.

5. In the Show method, I removed the node from its current collection, then cast the Node.Tag back to its proper original TreeView or TreeNode value, and then added the node object back into that parent’s Nodes collection.

Presto! A simple, efficient solution for temporarily hiding TreeNodes!

The full version of the class implements a custom structure to stuff more custom data into the Node.Tag property, a Dictionary to look up nodes by name (no matter which TreeView they’re in), and support for copying parent structures.

Add A Comment