At some point, you may want to search a tree view field to find out whether it contains a specific node. There are numerous ways to search tree view fields, and a complete discussion of them is beyond the scope of this manual. The following is the code for the TreeView_Search() function. You can use this code as a starting point for searching tree view fields.
function returns long node_found; inout anonymous field tree_field. {The tree field to search.} in long search_node; {The ID of the node to search from.} in string search_item; {The item to search for.} if search_node = TV_NODEINVALID then {The search node is not valid.} node_found = TV_NODEINVALID; else if TreeView_GetNodeLabel(tree_field, search_node) = search_item then {The search item was found.} node_found = search_node; else {If the search node has children, search them.} node_found = TreeView_Search(tree_field, TreeView_GetFirstChild (tree_field, search_node), search_item); if node_found = TV_NODEINVALID then {There are no children, so search the next sibling.} node_found = TreeView_Search(tree_field, TreeView_GetNextNode(tree_field, search_node), search_item); end if; end if; end if;
The TreeView_Search() function begins searching the tree at the node specified. If a node having the specific label is found, that node’s ID is returned. Otherwise, a value corresponding to the TV_NODEINVALID constant is returned.
This is a depth-first search, meaning that child nodes are searched before sibling nodes. To make this a breadth-first search, in which sibling nodes are searched before child nodes, simply swap the two shaded sanScript statements in the script above.
This is a depth-first search, meaning that child nodes are searched before sibling nodes. To make this a breadth-first search, in which sibling nodes are searched before child nodes, simply swap the two sanScript statements indicated in the above illustration.
The TreeView_Search() function is recursive, meaning the function makes calls to itself. Many searching algorithms can be coded more efficiently if recursion is used. |
The following example uses the TreeView_Search() function to search the Houses Tree field for the first node whose label is “Fargo”, beginning with the first root-level node.
local long node_ID; local boolean result; node_ID = TreeView_Search('Houses Tree', TreeView_GetRootNode ('Houses Tree'), "Fargo"); {If a node was found, select it.} if node_ID <> TV_NODEINVALID then result = TreeView_SetSelectedNode('Houses Tree', node_ID); end if;