Function for popular TTreeview only adds childs to the first node

1

I created this procedure to populate a treeview:

procedure TFrmGerProfDock.Button1Click(Sender: TObject);
Var
Tables: TTreeNode;
I: Integer;
begin
  for I := 0 to ds.DataSet.FieldCount - 1 do
  begin
    TreeView1.Items.BeginUpdate;
    TreeView1.Items.Add(nil, ds.DataSet.Fields[I].FieldName); //adiciona um node novo
    while not ds.DataSet.Eof do
    begin
      TreeView1.Items.AddChild(TreeView1.Items[I],
        ds.DataSet.Fields[I].AsString);//adiciona ao node novos childs
      ds.DataSet.Next;
    end;
    ds.DataSet.First;
    TreeView1.Items.EndUpdate;

  end;
end;

The problem is that procedure always adds childs to the first node, what would be wrong in this code?

    
asked by anonymous 25.06.2015 / 16:52

1 answer

1

You need to save the parent Node reference, use the Tables variable you created.

Var
  Tables: TTreeNode;
  Root : TTreeNode;
  I: Integer;
begin
  TreeView1.Items.BeginUpdate;
  //Incluir Root
  Root := TreeView1.Items.Add(nil, 'Root'); 
  for I := 0 to ds.DataSet..FieldCount - 1 do
  begin
    // Guarde o node Pai
    Tables := TreeView1.Items.Add(Root, ds.DataSet..Fields[I].FieldName);                
    //adiciona um node novo
    while not ClientDataset1.Eof do
    begin
      //Aqui você inclui no pai
      TreeView1.Items.AddChild(Tables,
        ds.DataSet..Fields[I].AsString);//adiciona ao node novos childs
      ds.DataSet..Next;
    end;
    ds.DataSet..First;   
  end;
  TreeView1.Items.EndUpdate; //O Begin e End update não podem ficar dentro de um loop, isso faz eles ficaram piscando.
end;
    
25.06.2015 / 20:48