在数据库中建一张表,包含:NodeName,NodeId,ParentId 3个字段,具体什么含义,一看就知了。
过程如下:
procedure TFRM_channel.formtreenode(parentid:string;TreeView1: TTreeView;parentnode:TTreeNode;ADOQuery1:TADOQuery);
var
i:integer;
treenode:TTreeNode;
begin
i:=0;
ADOQuery1.First;
while not ADOQuery1.Eof do
begin
if ADOQuery1.FieldByName('ParentId').AsString=parentid then
begin
treenode:=TreeView1.Items.AddChild(parentnode,ADOQuery1.fieldbyname('NodeName').AsString);
formtreenode(ADOQuery1.fieldbyname('NodeId').AsString ,TreeView1,treenode,ADOQuery1);
end;
inc(i);
ADOQuery1.First;
ADOQuery1.MoveBy(i);
end;
end;
在调用如下,如在窗体的create事件中:
procedure TFRM_channel.FormCreate(Sender: TObject);
var
TreeNode1:TTreeNode;
i:integer;
nodename:string;
nodeid:string;
parentid:string;
cmdstr:string;
begin
//初始化树形节点
ADOQuery1.ConnectionString:=mypublic.datastr;
cmdstr:='select * from ChanTreeNode order by ParentId ,NodeId asc';
ADOQuery1.Close;
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add(cmdstr);
ADOQuery1.Open;
TreeNode1:=nil;
formtreenode('000',TreeView1,TreeNode1,ADOQuery1);
end;