C# Programming > Miscellaneous

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...

There is simple way, however, using the Dictionary data structure.

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.

private Dictionary<string, bool> SaveTreeState(TreeView tree)
{
     Dictionary<string, bool> nodeStates = new Dictionary<string, bool>();
     for (int i = 0; i < tree.Nodes.Count; i++)
     {
          if (tree.Nodes[i].Nodes.Count > 0)
          {
              nodeStates.Add(tree.Nodes[i].Name, tree.Nodes[i].IsExpanded);
          }
     }

     return nodeStates;
}

Load TreeView State

Once the TreeView state is saved, loading the TreeView state is just as simple:

private void RestoreTreeState(TreeView tree, Dictionary<string, bool> treeState)
{
     for (int i = 0; i < tree.Nodes.Count; i++)
     {
          if (treeState.ContainsKey(tree.Nodes[i].Name))
          {
              if (treeState[tree.Nodes[i].Name])
                  tree.Nodes[i].Expand();
              else
                  tree.Nodes[i].Collapse();
          }
     }
}

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...

Back to C# Article List