Add and Remove Items in a Treeview Control

File: ...\Samples\Solution\OLE\Bldtree.scx

A treeview control displays a collection of Node objects, each of which consists of a label and an optional bitmap. After creating a treeview control, you can add, remove, arrange, and otherwise manipulate Node objects by setting properties and invoking methods.

This sample illustrates adding nodes to a treeview control, deleting nodes, selecting nodes programmatically, writing a treeview hierarchy to a table, and reading a treeview hierarchy from a table.

Adding Nodes

Each node in a treeview control needs to have a unique key that is a character string, generated by the NewKey method in this sample form.

*NewKey method
cKey = THIS.cNextKey
THIS.cNextKey = ALLTRIM(STR(VAL(THIS.cNextKey) + 1) + "_")
RETURN cKey

The Add method of the treeview control is used to add new nodes. The code associated with the Click event of cmdNewNode adds a root level node using the Add method.

o = THISFORM.oleTree
o.Nodes.Add(,1,THISFORM.NewKey(),"Click to edit text",0)

The code associated with the Click event of cmdNewChild adds a node as a child of the currently selected node.

o = THISFORM.oleTree
IF !ISNULL(o.SelectedItem) THEN
   o.Nodes.Add(o.SelectedItem.Key, 4, THISFORM.NewKey(), "Click to edit text",0)
ENDIF

Deleting Nodes

You can delete all of the nodes by calling the Clear method.

THISFORM.oleTree.Nodes.Clear

Or you can use the Remove method to delete selected nodes. All children of the deleted node are also deleted.

THISFORM.oleTree.Nodes.Remove(THISFORM.oleTree.SelectedItem.Key)

Writing and Reading Hierarchies in Tables

To save your treeview hierarchy in a table so you can reload it and edit it, loop through all the nodes in the treeview control and write the Key, the parent node's Key, and the Text to the appropriate fields of a table.

FOR i = 1 TO loNodes.Count
   IF ISNULL(loNodes.Item(i).Parent)
      lcParent = "0_" && Root
   ELSE
      lcParent = loNodes.Item(i).Parent.Key
   ENDIF
   INSERT INTO (lcDBFName) VALUES ;
      (loNodes.Item(i).Key, ;
       lcParent, ;
       loNodes.Item(i).Text)
ENDFOR

To reconstruct the treeview hierarchy, scan through the records in the table, using the parent key, key, and text values that you previously stored.

* Fill the TreeView control with values in the table.
o = THISFORM.oleTree.Nodes
   SCAN
      IF ALLTRIM(parent) = '0_'
         o.add(,1,ALLTRIM(key),ALLTRIM(text),0)
      ELSE
         o.add(ALLTRIM(parent),4,ALLTRIM(key), ALLTRIM(text),0)
      ENDIF
      THISFORM.cNextKey = ALLTRIM(STR(VAL(key) + 1) + "_")
   ENDSCAN

See Also

Treeview/Listbox Drag and Drop | Solutions Samples