After adding a TreeNode to the .NET TreeView, it's IsExpanded property turns false, any idea why?
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?
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.
You should call ExpandAll after TreeView was build.
recently, i have encountered this problem too, you can see below thread,may be help for you. the reason is treeview have not been rendered yet. you can do TreeNode.Expand() after render then will be ok.
treenode.IsExpanded still false after excute treenode.expand
精彩评论