当前位置 : 主页 > 编程语言 > delphi >

在DELPHI中用TreeView控件从数据库中动态装载信息

来源:互联网 收集:自由互联 发布时间:2021-06-23
1.PInfo表结构ID VARCHAR(50)FullName VARCHAR(50)ParentID VARCHAR(50)2.Unit文件unit Info;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, DB, ADODB;type PNodeInfo=^TNod

1.PInfo表结构ID VARCHAR(50)FullName VARCHAR(50)ParentID VARCHAR(50)2.Unit文件unit Info;interfaceuses  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.  

网友评论