如何基于记录集填充树视图

时间:2017-12-31 12:07:41

标签: delphi treeview

从下面的查询

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

我有一个这样的记录集:

Db recordset

我需要在树视图中显示数据:

enter image description here

我坚持使用下面的代码。

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;

我得到的结果如下,这不是我想要的:

enter image description here

1 个答案:

答案 0 :(得分:4)

经过一顿丰盛的午餐,我的思绪重生,然后我找到了解决方案。

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;

然后结果如下:

enter image description here