Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand a new added node in TreeView

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.

like image 298
Leonardo Brogelli Avatar asked Oct 29 '25 00:10

Leonardo Brogelli


2 Answers

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();
like image 162
Reza Aghaei Avatar answered Oct 30 '25 15:10

Reza Aghaei


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.

like image 32
Stefan PEev Avatar answered Oct 30 '25 17:10

Stefan PEev