'How to add nodes to FireMonkey's TreeView at runtime

I can't found any sample in the online documentation, or in the demos included with Delphi XE2, for adding nodes to a FMX.TreeView.TTreeView control at runtime. So, how can I add, remove, and traverse nodes of a FireMonkey TreeView at runtime?



Solution 1:[1]

I think we are all learning at this point...

But from what I have seen the TTreeView use the principle that any control can parent another control.

All you need to do is set the Parent Property to get the item to show up as a child.

var
  Item1 : TTreeViewItem;
  Item2 : TTreeViewItem;
begin
  Item1 := TTreeViewItem.Create(Self);
  Item1.Text := 'My First Node';
  Item1.Parent := TreeView1;

  Item2 := TTreeViewItem.Create(Self);
  Item2.Text := 'My Child Node';
  Item2.Parent := Item1;
end;

Because of this you can do things never possible before, such as placing any control in the TreeView. For example this code will add a button to the area used by Item2, and the button won't be visible until the Item2 is visible.

  Button := TButton.Create(self);
  Button.Text := 'A Button';
  Button.Position.X := 100;
  Button.Parent := Item2;

Solution 2:[2]

With AddObject(FmxObject) you can add any Object (Button etc.) as well...

Solution 3:[3]

I have another idea. The first answer helped me get it. So Add the following code

Var
TempItem:TTreeViewItem;
Begin
TempItem := TTreeViewItem.Create(Self);
TempItem.Text := 'Enter Caption Here';
TempItem.Parent := TreeView;  
End

Now the actual trick comes when you have to free the item so that it doesn't use unnecessary memory. So lets say you use it in a loop, like I did here:

ADOTable.Connection := ADOConnection;
  ADOTable.TableName := 'MenuTree';

  ADOTable.Open;
  ADOTable.First;

  ADOTable.Filter := '(CHFlag=''CURRENT'') AND (Parent=''Tree'')';
  ADOTable.Filtered := True;

  While NOT ADOTable.Eof Do
    Begin
      TempItem := TTreeViewItem.Create(Self);
      TempItem.Text := ADOTable['ItemName'];
      TempItem.Parent := TreeView;
      // TempItem.Free;

      ADOTable.Next;
    End;
  TempItem.Free;
  ADOTable.Close;

Solution 4:[4]

Your code isn't secure. If ADOTable is empty, TempItem is never created and the 'free' will generate an access violation. And even if the table is not empty, you will only free the last TempItem created.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Robert Love
Solution 2 Hartmut Hamker
Solution 3 Jacques Koekemoer
Solution 4 Ygo