// add by cxg 2017-4-18
unit uTree;
interface
uses
SysUtils, Classes, ComCtrls, DB, DBClient;
type
PNodeRec = ^TNodeRec;
TNodeRec = record // 树节点记录
id: string;
name: string;
pid: string;
formname: string; // add by cxg 2017-2-14
bplname: string; // add by cxg 2017-4-18
end;
procedure CreateTree(dataset: TClientDataSet; treeview: TTreeView; id, aname, parentid: string);
procedure FreeTree(treeview: TTreeView);
implementation
procedure CreateTree(dataset: TClientDataSet; treeview: TTreeView; id, aname, parentid: string);
// table struct example: id,name,pid
var
List: TStringList;
Node: TTreeNode;
Index: Integer;
PNode: PNodeRec;
begin
if not dataset.Active or dataset.IsEmpty then
Exit;
treeview.Items.Clear;
List := TStringList.Create;
try
List.Sorted := True;
dataset.First;
while not dataset.Eof do
begin
PNode := new(PNodeRec);
PNode^.id := dataset.FieldByName(id).Text;
PNode^.name := dataset.FieldByName(aname).Text;
PNode^.pid := dataset.FieldByName(parentid).Text;
// add by cxg 2017-2-14
if dataset.FindField(‘formname‘) <> nil then
PNode.formname := dataset.FindField(‘formname‘).Text;
// add by cxg 2017-4-18
if dataset.FindField(‘bplname‘) <> nil then
PNode.bplname := dataset.FindField(‘bplname‘).Text;
if (dataset.FieldByName(parentid).Text = ‘‘) or (dataset.FieldByName(id).Text = dataset.FieldByName(parentid).Text) then
// add root node
Node := treeview.Items.AddChild(nil, dataset.FieldByName(aname).Text)
else
begin
// add child node
Index := List.IndexOf(dataset.FieldByName(parentid).Text);
Node := treeview.Items.AddChild(TTreeNode(List.Objects[Index]), dataset.FieldByName(aname).Text);
end;
Node.Data := PNode;
List.AddObject(dataset.FieldByName(id).Text, Node);
dataset.Next;
end;
finally
List.Free;
end;
end;
procedure FreeTree(treeview: TTreeView);
var
i: Integer;
Node: TTreeNode;
begin
for i := treeview.Items.Count - 1 downto 0 do
begin
Node := treeview.Items[i];
Dispose(PNodeRec(Node.Data));
end;
end;
end.