Save TreeView State

C# TreeView

The C# TreeView control is an extensive topic. It is a simple way to organize information in C# applications. CodeProject, a large programming website, has hundreds of articles just on TreeView controls.

So for example, let's say you have a C# program that builds a TreeView programmatically. Since elements are dynamic, the TreeView is cleared and repopulated every time a single Node is changed.

Unfortunately there is no way to automatically preserve the expanded and collapsed state of TreeNodes whenever the TreeView is filled...

Save TreeView State

The concept is simple to maintain a TreeView state: iterate through the top level Nodes of a TreeView and save whether the node was expanded or collapsed. Notice that to keep things simple, the source code only saves the state of top-level nodes.

The C# functions Expand and Collapse make it simple to set the previous state of the TreeView nodes. By the way, the tree parameter is a reference by default, meaning any changes made to the TreeView state are applied to the original TreeView...