At design time, you can add nodes to a TreeView control by clicking the Nodes property in the Properties window to display the TreeNode Editor (shown in Figure 3-6). You can add new root nodes or new child nodes and set the properties of each TreeNode.
At run time, you can create new TreeNode objects and add them as root nodes to the TreeView control or add them as child nodes to another TreeNode. For both of these procedures, you use the Nodes.Add method, as shown here:
Dim aNode As New TreeNode("New Node") ' Add a child node to the new node aNode.Nodes.Add(New TreeNode("New Child"))
' Adds aNode and its child As a new root node in a TreeView control named TreeView1 TreeView1.Nodes.Add(aNode)
' Adds a second child node to the first node in TreeView1 TreeView1.Nodes(0).Nodes.Add(New TreeNode("Second Child"))
TreeNode aNode = new TreeNode("New Node"); // Add a child node to the new node aNode.Nodes.Add(new TreeNode("New Child"));
// Adds aNode and its child as a new root node in a TreeView control named TreeView1 treeView1.Nodes.Add(aNode);
// Adds a second child node to the first node in TreeView1 treeView1.Nodes.Nodes.Add(new TreeNode("Second Child"));
You can remove nodes from the Nodes collection by using the Remove and RemoveAt methods. The Remove method takes a reference to a particular node as a parameter and removes it from the collection if it exists in the collection. If the specified node does not exist in the collection, this method call is ignored. The RemoveAt method removes the node at a specified index. If the specified index is not present in the nodes collection, an ArgumentOutOfRange exception is thrown. The following example demonstrates the Remove and RemoveAt methods.
' Removes the node named aNode from the collection TreeView1.Nodes.Remove(aNode)
' Removes the node at index 3 from the collection. TreeView1.Nodes.RemoveAt(3)
// Removes the node named aNode from the collection treeView1.Nodes.Remove(aNode);
// Removes the node at index 3 from the collection. treeView1.Nodes.RemoveAt(3);
Was this article helpful?