I have a TreeView in my form, I need to add programmatically a new node on particolar mouse event. Then I need to expand the tree just to the new added node. I try to call the function Expand() on the new added node but I does not works.
This is a snippet of my code:
TreeNodeCollection tree = treeViewProtocolli.Nodes["Radice"].Nodes["ModBus"].Nodes;
if (tree != null)
{
    TreeNode node = new TreeNode();
    node.Text = "MBRTU";
    node.Name = "MBRTU";
    node.Tag = "BASE";
    node.ForeColor = System.Drawing.Color.Red;
    tree.Add(node);
TreeNode skBase = treeViewProtocolli.Nodes["Radice"].Nodes["ModBus"].Nodes["MBRTU"];
    if(skBase != null)
    {
        TreeNode sknode = new TreeNode();
        sknode.Text = nome + " -> [Slave = " + slave + " | Indirizzo = " + indirizzo +
                " | Funzione = " + funzione + " | Abilitato = " + abil + " | Lunghezza blocco = " + lunghezza + "]";
        sknode.Name = "MBRTU";
        skBase.Nodes.Add(sknode);
        sknode.Expand();
    }
}
Any suggestion? Thanks.
You can call EnsureVisible method of node. It ensures that the tree node is visible, expanding tree nodes and scrolling the tree view control as necessary.
For example:
var node = treeView1.Nodes[0].Nodes[0].Nodes.Add("something");
node.EnsureVisible();
Use TreeNode.Expand() on every node from the root to the leaf you wanted to be expanded, using Expand on the leaf node or the node you want to expand make only the node itself to show its subchildren.
ex. root -> nextnode1 -> somennode2 
If you want to be expanded truout somennode2 you should expand all of its parrent nodes (root.expand,nextnode1.expand and if you want you last node expanded somennode2.expand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With