How To Add and Removes Nodes at
Runtime
This sample shows How to add nodes to a Treeview at
runtime.
For the sample code to run you will need to do the following
things:
1. Add from the components list Microsoft Windows Common
controls 5.0(Vb5) or 6.0(Vb6).
2. Add an Imagelist, a Treeview Control, 2 command buttons,2
textboxes, 2 option buttons, and a frame to your form.
3. The option buttons should be on the frame.
4. Name one option button OpParent with a caption of
Parent.
5. Name the other option button OpChild with a caption of
Child.
6. Add 2 pictures to the Imagelist.
Option Explicit
Dim tn As Node
Dim img As ImageList
Private Sub Command1_Click()
'This procedure adds nodes
On Error GoTo errhan:
'This sets focus to the treeview
TreeView1.SetFocus
'This checks if the parent option button is
selected so it knows to add a parent node
If Opparent.Value = True Then
'this adds the parent node
Set tn = TreeView1.Nodes.Add(, , Text1.Text,
"Parent1" & Text1.Text, 1, 1)
'This checks if the child option button is
selected so it knows to add a child node
ElseIf Opchild.Value = True Then
'this adds the child node
Set tn =
TreeView1.Nodes.Add(TreeView1.SelectedItem, tvwChild,
Text1.Text, "child" & Text1.Text, 2, 2)
End If
Exit Sub
errhan:
'This is a procedure that checks for
errors
ErrorH
End Sub
Private Sub Command2_Click()
'This procedure deletes nodes 'This loops thru the nodes collection
For Each tn In TreeView1.Nodes
'and checks all the nodes to see if the
node selected to be deleted exists first
If tn.Key = Text2.Text Then
'Then delete the specified node
TreeView1.Nodes.Remove tn.Key
'then exits the loop after it has been
deleted
Exit For
End If
Next
End Sub
Private Sub Form_Load()
Opparent.Value = True Command1.caption="Add Node"
Command2.caption="Remove Node"
TreeView1.ImageList = ImageList1 'this will initialize the
Imagelist
'this adds the first parent node to the
treeview
Set tn = TreeView1.Nodes.Add(, , "p1", "Parent1", 1, 1)
'this make the parent node expanded
TreeView1.Nodes(1).Expanded = True
'this adds the first child node
Set tn = TreeView1.Nodes.Add("p1", tvwChild, "c1",
"child1", 2, 2)
End Sub
Public Sub ErrorH()
'this is the error
handler.
'this checks for a specific error this error is caused if you
try to add a key value that already exist
If Err.Number = 35602 Then
'if the above error occurs then a msgbox
pops up saying choose another key
MsgBox "Choose a different key the value you requested
already exists"
Else
'else it just gives the error number and
description
MsgBox "Error number:" & Err.Number & "Error
Description:" & Err.Description
End If
End Sub