1.PInfo表结构
ID VARCHAR(50)
FullName VARCHAR(50)
ParentID VARCHAR(50)
2.Unit文件
unit Info;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, DB, ADODB;
type
PNodeInfo=^TNodeInfo;
TNodeInfo=record
ID:string;
FullName:string;
end;
TfmInfo = class(TForm)
TreeView1: TTreeView;
btnShowInfo: TButton;
ADOQuery1: TADOQuery;
ADOConnection1: TADOConnection;
procedure CreateChildTree(ParentNode: TTreeNode);
procedure btnShowInfoClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmInfo: TfmInfo;
implementation
{$R *.dfm}
//创建子树
procedure TfmInfo.CreateChildTree(ParentNode: TTreeNode);
var
Query:TADOQuery;
ChildNode:TTreeNode; //孩子结点
ChildNodeInfo:PNodeInfo; //孩子结点信息
begin
Query:=TADOQuery.Create(nil);
with Query do
begin
Connection:=ADOConnection1;
SQL.Add('SELECT ID,FullName FROM PInfo WHERE ParentID = '''+PNodeInfo(ParentNode.Data)^.ID+''''); //获取孩子结点信息
Open;
while not Eof do
begin
New(ChildNodeInfo);
ChildNodeInfo^.ID:=FieldByName('ID').AsString;
ChildNodeInfo^.FullName:=FieldByName('FullName').AsString;
ChildNode:=TreeView1.Items.AddChildObject(ParentNode,(ChildNodeInfo^.ID+ChildNodeInfo^.FullName),ChildNodeInfo); //添加孩子结点,并关联孩子结点信息
CreateChildTree(ChildNode); //进行递归
Next;
end;
Close;
end;
end;
procedure TfmInfo.btnShowInfoClick(Sender: TObject);
var
BootNode:TTreeNode; //根结点
BootNodeInfo:PNodeInfo; //根结点信息
begin
with ADOQuery1 do
begin
SQL.Clear;
SQL.Add('SELECT ID,FullName FROM PInfo WHERE ParentID IS NULL'); //获取根结点信息
Open;
New(BootNodeInfo);
BootNodeInfo^.ID:=FieldByName('ID').AsString;
BootNodeInfo^.FullName:=FieldByName('FullName').AsString;
TreeView1.Items.Clear;
BootNode:=TreeView1.Items.AddChildObject(nil,(BootNodeInfo^.ID+BootNodeInfo^.FullName),BootNodeInfo); //添加根结点,并关联根结点信息
Close;
end;
CreateChildTree(BootNode); //创建子树
TreeView1.FullExpand; //展开所有树结点
end;
end.