Search code examples
c#treeview

Expand selected node after refresh TreeView in C#


I have a treeview with many items

When I expand an item and its childs and after I called refresh method, that expanded item childs becomes collapsed.

Can you give me an idea how to store the selected node and after refresh, to call the Expand method again...

I tried :

 TreeNode selectedNode = new TreeNode();
 TreeNode selectedNode = SelectedTreeNode();  //method which takes selected node from TV
 RestoreFolderTreeWithLastSelectedItem(); //method which initialise treeview object
 //here I want to call Expand() method but it not exists to TreeNode.

For treeview, I used Windows.Controls.treeView namespace I am beginner... Thank you

I will explain you via images

I expanded all items: enter image description here

If I press F5 or call Refresh function (RestoreFolderTreeWithLastSelectedItem();) then they will be collapsed like as:

enter image description here

instead of first image...


Solution

  • I'm using this with a WinForms TreeView. It saves the nodes expanded state between refreshes:

    // Save the path of the expanded tree branches
    var savedExpansionState = treeView1.Nodes.GetExpansionState();
    
    treeView1.BeginUpdate();
    
    // TreeView is populated
    // ...
    
    // Once it is populated, we need to restore expanded nodes
    treeView1.Nodes.SetExpansionState(savedExpansionState);
    
    treeView1.EndUpdate();
    

    Here is the code to achieve this:

    public static class TreeViewExtensions
    {
        public static List<string> GetExpansionState(this TreeNodeCollection nodes)
        {
            return nodes.Descendants()
                        .Where(n => n.IsExpanded)
                        .Select(n => n.FullPath)
                        .ToList();
        }
    
        public static void SetExpansionState(this TreeNodeCollection nodes, List<string> savedExpansionState)
        {
            foreach (var node in nodes.Descendants()
                                      .Where(n => savedExpansionState.Contains(n.FullPath)))
            {
                node.Expand();
            }
        }
    
        public static IEnumerable<TreeNode> Descendants(this TreeNodeCollection c)
        {
            foreach (var node in c.OfType<TreeNode>())
            {
                yield return node;
    
                foreach (var child in node.Nodes.Descendants())
                {
                    yield return child;
                }
            }
        }
    }