建树结构的原则就是先要有跟节点,才能建旗下的子节点,围绕这一矛盾展开,会有以下两种方法。
1.递归建树(数据表中有一个记录的parentid值为0,代表根节点)
procedure TForm1.createtree(Sender: TObject);
var
sqlstr:string;
i:Integer;
rootnode,parentnode:TTreeNode;
isfind:Boolean;
begin
adoquery1.Close;
ADOQuery1.SQL.Clear;
sqlstr:=''select * from tdepart'';
ADOQuery1.SQL.Add(sqlstr);
ADOQuery1.Open;
ADOQuery1.First;
while not ADOQuery1.Eof do
begin
i:=0;
isfind:=false;
for i:=0 to tv1.Items.Count-1 do
if ADOQuery1.fieldbyname(''departid'').Asinteger = integer(tv1.Items.item[i].Data) then
begin
isfind:=True;
Break;
end;
if not isfind then
createtreenode(ADOQuery1.fieldbyname(''departid'').Asinteger,
ADOQuery1.fieldbyname(''departname'').AsString,
ADOQuery1.fieldbyname(''parentid'').Asinteger);
adoquery1.Next;
end;
end;
procedure TForm1.createtreenode(id:Integer;depart:string;parentid:integer);
var
i,j,id1,parentid1:Integer;
rootnode,parentnode:TTreeNode;
isfind,isfind1:Boolean;
sqlstr,depart1:string;
begin
if parentid = 0 then
rootnode:=tv1.Items.addchildobject(nil,trim(depart),pointer(id))
else
begin
i:=0;
parentnode:=nil;
isfind:=false;
for i:=0 to tv1.Items.Count-1 do
if parentid = integer(tv1.Items.item[i].Data) then
begin
&nb