### Bookstore

 Computer Math and Games in Pascal (preview) Lazarus Handbook

### Author Topic: [Solved] How to loop through all child nodes?  (Read 306 times)

#### Hansvb

• Sr. Member
• Posts: 466
##### [Solved] How to loop through all child nodes?
« on: December 02, 2022, 09:06:44 pm »
Hi,
If I click on a node in a TreeView, I want to run through all the child nodes of the selected node. With the following I don't always run through all childs. It skips sometimes child nodes.
How can I get that done?

Code: Pascal  [Select][+][-]
1. procedure TFrm_Main.SelectChildren(ANode: TTreeNode);
2.  begin
3.    ANode := ANode.GetFirstChild;
4.    if ANode = nil then Exit;
5.    repeat
6.      TreeViewApi.Select(ANode, [ssCtrl]);
7.      SelectChildren(ANode);
8.
9.      ANode := ANode.getNextSibling;
10.
11.    until ANode = nil;
12. end;
« Last Edit: December 03, 2022, 03:57:16 pm by Hansvb »

#### jamie

• Hero Member
• Posts: 5165
##### Re: How to loop through all child nodes?
« Reply #1 on: December 02, 2022, 09:28:24 pm »
siblings

I think its the first firstchild and then next slibling etc
The only true wisdom is knowing you know nothing

#### wp

• Hero Member
• Posts: 10627
##### Re: How to loop through all child nodes?
« Reply #2 on: December 02, 2022, 10:29:45 pm »
First do with the node passed to SelectChildren what you have want to - here mark is as selected. Then you want to continue with its children. The first child is ANode.GetFirstChild, the next child is its next sibling, etc. For each child, call for it SelectChildren. Since this is a recursive call it will automatically propagate the selection to the children of the children etc.

Code: Pascal  [Select][+][-]
1. procedure TForm1.SelectChildren(ANode: TTreeNode);
2. begin
3.   if ANode = nil then
4.     exit;
5.   ANode.Selected := true;
6.   ANode := ANode.GetFirstChild;
7.   while ANode <> nil do begin
8.     SelectChildren(ANode);
9.     ANode := ANode.GetNextSibling;
10.   end;
11. end;
12.
13. procedure TForm1.TreeView1SelectionChanged(Sender: TObject);
14. begin
15.   TreeView1.BeginUpdate;
16.   SelectChildren(Treeview1.Selected);
17.   TreeView1.EndUpdate;
18. end;

#### Hansvb

• Sr. Member
• Posts: 466
##### Re: How to loop through all child nodes?
« Reply #3 on: December 03, 2022, 03:56:48 pm »

What I really wanted is to get all TreeNode.Text of all nodes from the selected node. This was achieved thanks to the example given.
Thanks again.