procedure TUIOperate.FillTree(treeview: TTreeView);
where
findq: TADOQuery;
node: TTreeNode;
// This method is based on the id field values of the records, to find the parent TreeView
function FindParentNode(id:Integer):TTreeNode;
where
i:Integer;
begin
Result := nil;
for i := 0 to treeview.Items.Count - 1 do
begin
// id value and compare the value of Node's Data records
if Integer(treeview.Items[i].Data) = id then
begin
Result := treeview.Items[i];
Break;
end;
end;
end;
begin
findq := TADOQuery.Create(nil);
findq.Connection: = controler.DataConnect.Connection; // Connection point where your data connection
try
treeview.Items.BeginUpdate;
treeview.Items.Clear;
// select all records, press parentid sort, so you can ensure to add top-level node, when you add a subordinate record, you can always find a parent
findq.SQL.Text := 'SELECT * FROM [Catalog] order by parentid,id';
findq.Open;
while not findq.Eof do
begin
// If the top, added directly to the Treeview
if findq.FieldByName('parentid').AsInteger = -1 then
// The id value, stored in the Data Node in order to find a
treeview.Items.AddObject(nil,findq.FieldByName('CatalogName').AsString,Pointer(findq.FieldByName('id').AsInteger))
else
begin
// Find the parent node
node := FindParentNode(findq.FieldByName('parentid').AsInteger);
if node <> nil then
treeview.Items.AddChildObject(node,findq.FieldByName('CatalogName').AsString,Pointer(findq.FieldByName('id').AsInteger));
end;
findq.Next;
end;
finally
findq.Free;
treeview.Items.EndUpdate;
end;
end;