C# TreeView – Preserve State

The TreeView control built-in to the .Net Framework is powerful but a bit basic. It takes some creativity to enhance its functionality. For example, how to preserve the expanded and collapsed state of nodes…

The reason to preserve the expanded/collapsed state of a tree node is to prevent users from getting disoriented when a node is added or removed from the TreeView. Fittingly, this occurs when a TreeView displays dynamic data.

When a TreeView control is populated with data, the previous content is usually cleared. Thus, if you want to preserve the TreeView state, you need to find a way to save the state, reload the data, then restore the state.

The idea is simple, its only downfall is it won’t work for sub nodes. We are going to have to make use of the Dictionary data structure.

The Dictionary will hold two values per entry, a string (for the node Name) and a boolean (for whether the node is expanded).

Once the values are stored in the Dictionary, the TreeView is cleared and repopulated with the new data. Then we can go back and for each entry in the Dictionary: check if the Node still exists, and if it does, use the functions Expand and Collapse to set the proper node state.

Notice that this is more light-weight than simply creating a copy of the TreeView as a reference. However, as mentioned above, this will only work with the top-level nodes. For more levels, then a reference copy of the TreeView will be necessary.