//table2(ID Primary Key, Name, ParentID)
//界面上有一TTreeView, ADOConnection, 两个ADOQuery
procedure TForm1.btn1Click(Sender: TObject);
var
s1, s2: string;
FNode: TTreeNode;
function MyFindTNode(PID: Integer): TTreeNode;
var
i: Integer;
begin
Result := nil;
for i := 0 to tv1.Items.Count - 1 do
begin
if tv1.Items.Data = nil then Continue;
if Integer(tv1.Items.Data) = PID then
Result := tv1.Items;
if Result <> nil then Break;
end;
end;
begin
tv1.Items.Clear;
s1 := 'Select * From table2 where ParentID = 0';
qry1.Close;
qry1.SQL.Clear;
qry1.SQL.Add(s1);
qry1.Open;
qry1.First;
while not qry1.Eof do
begin
tv1.Items.AddChildObject(nil, qry1.FieldByName('Name').AsString,
Pointer(qry1.FieldByName('ID').AsInteger));
qry1.Next;
end;
s2 := 'Select * From table2 where ParentID <> 0';
qry2.Close;
qry2.SQL.Clear;
qry2.SQL.Add(s2);
qry2.Open;
qry2.First;
while not qry2.Eof do
begin
FNode := MyFindTNode(qry2.FieldByName('ParentID').AsInteger);
if FNode <> nil then
tv1.Items.AddChildObject(FNode, qry2.FieldByName('Name').AsString,
Pointer(qry2.FieldByName('ID').AsInteger));
qry2.Next;
end;
end;