Friday, November 22, 2019
How to Locate TreeView Node By Text
How to Locate TreeView Node By Text While developing Delphi applications using the TreeView component, you may bump into a situation where you need to search for a tree node given by only the text of the node. In this article well present you with one quick and easy function to get TreeView node by text. A Delphi Example First, well build a simple Delphi form containing a TreeView, a Button, CheckBox and an Edit component- leave all the default component names. As you might imagine, the code will work something like:à if GetNodeByText given by Edit1.Text returns a node and MakeVisible (CheckBox1) is true then select node. The most important part is the GetNodeByText function. This function simply iterates through all the nodes inside theà ATreeà TreeView starting from the first node (ATree.Items[0]). The iteration uses theà GetNextà method of the TTreeView class to look for the next node in the ATree (looks inside all nodes of all child nodes). If the Node with text (label) given byà AValueà is found (case insensitive) the function returns the node. The boolean variableà AVisibleà is used to make the node visible (if hidden). function GetNodeByText(ATree : TTreeView; AValue:String; AVisible: Boolean): TTreeNode;var Node: TTreeNode;begin Result : nil; if ATree.Items.Count 0 then Exit; Node : ATree.Items[0]; while Node nil dobeginif UpperCase(Node.Text) UpperCase(AValue) thenbegin Result : Node; if AVisible then Result.MakeVisible; Break; end; Node : Node.GetNext; end;end; This is the code that runs the Find Node button OnClick event: procedure TForm1.Button1Click(Sender: TObject);var tn : TTreeNode;begin tn:GetNodeByText(TreeView1,Edit1.Text,CheckBox1.Checked); if tn nil then ShowMessage(Not found!) elsebegin TreeView1.SetFocus; tn.Selected : True; end;end; Note: If the node is located the code selects the node, if not a message is displayed. Thats it. As simple as only Delphi can be. However, if you look twice, youll see something is missing: the code will find the FIRST node given by AText.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.