Search code examples
treeviewlazarus

How do I load hierarchical data from a database into a tree view


I have a database table with data and need to load the fields into a TTreeView object.

The line:

ItemTree.Items.AddChild(nil, CurrentField_Text);

simply adds a node to the top level.

How can I specify a point to insert it in?

Please note that while looping through the data from the table, I may (for example) insert 3 top level items and then the 4th element is actually the child of node 2.

How can I specify this?


Solution

  • This is some code lifted directly from a program of mine which inserts values taken from a query into a treeview.

     tv.items.clear;
     with qCustTree do  // this is the query which 'feeds' the treeview
      try
       close;
       params[0].asinteger:= qCustWithCallsID.asinteger;
       open;
       tv.items.BeginUpdate;
      while not eof do
       begin
        father:= fieldbyname ('father').asinteger;
        if father = 0
         then node:= nil
         else node:= FindANode (father);
        lastnode:= tv.Items.AddChildObject (node, fieldbyname ('curdate').asstring,
                                            pointer (fieldbyname ('id').asinteger));
        next
       end;
      finally
       tv.items.endupdate;
       tv.fullexpand;
       tv.Selected:= tv.Items[0];
       tvchange (nil, tv.Selected);
      end;
    

    If the 'father' field of the returned tuple is 0, then a new parent node is opened on the tree, otherwise a new child node is opened.