Gianluca Colombo
Gianluca Colombo

Reputation: 829

How to populate a tree view based on recordset

From the query below

Select FIELD1,FIELD2,FIELD3,FIELD4 FROM MyTable Order By FIELD1,FIELD2,FIELD3,FIELD4 Group By FIELD1,FIELD2,FIELD3,FIELD4

I have a recordset like this:

Db recordset

I need to show data in a treeview like this:

enter image description here

I'm stuck with the code below.

var
  Node: TTreeNode;
  RootLevelCount: Integer;
  X: Integer;
  CurrentTextField: String;
  MyTreeNodeText: array [0..10] of String;
begin

   RootLevelCount := 4; 

   while not dm1.Q1.Eof do
     begin
       for X := 0 to RootLevelCount do
        begin
          CurrentTextField:=dm1.Q1.Fields[x].AsString;
          if CurrentTextField='' then CurrentTextField := 'Level '+IntToStr(x);
          if MyTreeNodeText[x]<>CurrentTextField then
            begin
              MyTreeNodeText[X]:=CurrentTextField;
              if x=0 then
                begin
                 Node:=tree.Items.AddFirst(Node, CurrentTextField);
                end else
                begin
                 node:=tree.Items.AddChild(node.Parent, CurrentTextField);
                end;
            end else
            begin
                 node.GetNext;
            end;
        end;
        dm1.Q1.Next;
     end;

The result I have is the following and it's not I want:

enter image description here

Upvotes: 0

Views: 832

Answers (1)

Gianluca Colombo
Gianluca Colombo

Reputation: 829

After a good lunch, my mind has reborn then I found the solution.

var
  Node: TTreeNode;
  RootLevelCount: Integer;
  X,X1: Integer;
  CurrentTextField: String;
  MyTreeNodeText: array [0..10] of String;
  MyTreeNode: array [0..10] of TTreeNode;
begin

   RootLevelCount := 4; //Number of fields that you want to show in the treeview

   while not dm1.Q1.Eof do
     begin
       ROW_ID:=dm1.Q1.FieldByName('ROW_ID').AsString;
       for X := 0 to RootLevelCount-1 do
        begin
          CurrentTextField:=dm1.Q1.Fields[4+x].AsString;
          if CurrentTextField='' then CurrentTextField := 'Level '+IntToStr(x);
          if MyTreeNodeText[x]<>CurrentTextField then
            begin
              MyTreeNodeText[X]:=CurrentTextField;
              for X1 := x+1 to RootLevelCount-1 do
                MyTreeNodeText[x1]:='';
              if x=0 then
                begin
                 Node:=tree.Items.Add(nil, CurrentTextField);
                 TMyTreeNode(Node).Indice:=StrToInt(ROW_ID);
                 MyTreeNode[x]:=node;
                end else
                begin
                 node:=tree.Items.AddChild(MyTreeNode[x-1], CurrentTextField);
                 TMyTreeNode(Node).Indice:=StrToInt(ROW_ID);
                 MyTreeNode[x]:=node;
                end;
            end;
        end;
        MyTreeNodeText[RootLevelCount]:='';
        dm1.Q1.Next;
     end;

then the result is the following:

enter image description here

Upvotes: 4

Related Questions