delphi 根据数据库结构生成TreeView
作者:互联网
procedure TUIOperate.FillTree(treeview: TTreeView);
var
findq: TADOQuery;
node: TTreeNode;
//这个方法是根据记录的id字段值,查找TreeView上的父节点
function FindParentNode(id:Integer):TTreeNode;
var
i:Integer;
begin
Result := nil;
for i := 0 to treeview.Items.Count - 1 do
begin
//比较Node的Data值和记录的id值
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指向你的数据连接
try
treeview.Items.BeginUpdate;
treeview.Items.Clear;
//选出所有记录,并按parentid排序,这样可以保证先添加顶级节点,在下级记录添加时,总能找到父节点
findq.SQL.Text := 'SELECT * FROM [Catalog] order by parentid,id';
findq.Open;
while not findq.Eof do
begin
//如果是最顶级,直接添加到Treeview
if findq.FieldByName('parentid').AsInteger = -1 then
//将id值,保存在Node的Data中,以便查找用
treeview.Items.AddObject(nil,findq.FieldByName('CatalogName').AsString,Pointer(findq.FieldByName('id').AsInteger))
else
begin
//查找上级节点
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;
标签:TreeView,end,Items,delphi,id,FieldByName,treeview,数据库,findq 来源: https://www.cnblogs.com/jijm123/p/11372966.html