1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

Get TreeView Node By Text - Part 2
How to locate (search and select) a TreeView node given by the parent node and the searched node text.
 More of this Feature
• Part 1
 Join the Discussion
"Post your views, comments, questions and doubts to this article."
 Related Resources
• VCL Using articles
• Beginners Delphi Section

Intro...If you look twice, you'll see something is missing: the code will find the FIRST node given by AText! What if you want to search for a node at the same level as the calling node - where this calling node is also provided to the function!...

The above text issued a challenge to enhance the TreeView search algorithm introduced in the part 1 of this article: Get TreeView Node By Text.

Remember, we had a treeview component "filled" with nodes. The problem was to search (locate and make visible) the treeview node in a function that receives the node text as the parameter.

Look the picture below, we have a node with the caption "Button" under the "Standard" node. If we are to have the "Button" node below (as a child node) the "Additional" node, the function will find the first "Button" - the one under "Standard".

What we now want, is to tell the function to search for "Button" under "Additional"...

Delphi : Get TreeView Node by Text

We enhance the GetNodeByText function by adding one more parameter - the "InNode" node.

function GetNodeByText
  (ATree : TTreeView; InNode : TTreeNode; 
   AValue:String; AVisible:boolean) : TTreeNode;
  NodeText : String;
  NextNode : TTreeNode;
  Result := nil;
  NextNode := InNode.GetFirstChild;
  while NextNode  nil do
    NodeText := NextNode.Text;
    if UpperCase(NodeText) = UpperCase(AValue) then
       NextNode.Selected := AVisible;
      NextNode := NextNode.getNextSibling;
  end; //while
  Result := NextNode;

The function simply iterates through all the first level child nodes of the provided "InNode" node and looks for a node labeled AValue.

The code that runs the 'Find Node' button OnClick event is slightly modified. The second parameter is the "root" node for the search - for example the selected node.

procedure TForm1.Button1Click(Sender: TObject);
  tn : TTreeNode;
   tn:=GetNodeByText(TreeView1, TreeView1.Selected,
   if tn = nil then
     ShowMessage('Not found!')

That's it. If you have any questions please use the Delphi Programming Forum.

©2017 About.com. All rights reserved.