views:

52

answers:

2

I have a TreeView control on a form. I am dynamically adding new TreeNodes to it, and I am calling Expand() on them prior to adding them. This causes their IsExpanded property to be true. However immediately after adding it to the TreeView, or to any node on the TreeView, its IsExpanded property turns false and none of the nodes are expanded. Can anyone think of an idea why this would be? I even tried calling ExpandAll on the TreeView prior to adding any nodes. Does this method have to be called after adding a TreeNode to the TreeView or one of its existing children?

A: 

You should call ExpandAll after TreeView was build.

sashaeve
Doesn't ExpandAll() expand ALL children? I have some that when I created them have IsExpanded as false, and some as true. Will ExpandAll() respect this? If so it's misnamed. If not then I don't think this solves my issue.
Leeks and Leaks
+1  A: 

It seems that if when a TreeNode is added to a TreeView, and it doesn't have any children assigned to it, the IsExpanded property of that node is set to false. So using the code below:

private void Form1_Load(object sender, EventArgs e)

    {
        TreeNode node = new TreeNode();
        TreeNode cn1 = new TreeNode();
        TreeNode cn2 = new TreeNode();
        node.Text = "Hello";
        node.Nodes.Add(cn1);
        node.Nodes.Add(cn2);
        node.Expand();
        treeView1.Nodes.Add(node);
        bool expanded = node.IsExpanded;
    }

I found in this sample that if there were TreeNodes added as children, then the IsExpanded property remained true before and after it was added to the TreeView. So make sure the added node has child nodes or the TreeNodeCollection.Add() will change it to collapsed. Not sure of the why on this one, but hope it is helpful.

As for ExpandAll(), you will definitely have to call it after all children have been added. I don't know for sure, but I would assume it just iterates through each node's nodes recursively and calls "expand", so if the node to expand hasn't been added yet, it will be missed by this function.

lividsquirrel
Thanks for that, it explains a lot. However it's very annoying. I'm trying to deserialize a treeview that I had saved and I have container nodes that are deserialized prior to their children, which means I then have to go back for a 2nd pass to re-expand them after their children are added?Also you state that I still have to call ExpandAll()? Why is that? Won't ExpandAll() expand every node in the tree? That seems to defeat the purpose of individually expanding only those nodes that you want to expand.
Leeks and Leaks