树的一些操作

生成一棵树方法一:
procedure MakeTree(Query: TQuery; TreeView: TTreeView);
var
List: TStringList;
Node: TTreeNode;
Index: Integer;
begin
TreeView.Items.BeginUpdate;
try
TreeView.Items.Clear;

List := TStringList.Create;
try
List.Sorted := True;

while not Query.Eof do
begin
if Query.FieldByName('ParentID').AsInteger = 0 then { ParentID=0,顶层节点 }
Node := TreeView.Items.AddChild(nil, Query.FieldByName('Name').AsString)
else
begin
Index := List.IndexOf(Query.FieldByName('ParentID').AsString);
Node := TreeView.Items.AddChild(TTreeNode(List.Objects[Index]),
Query.FieldByName('Name').AsString);
end;
List.AddObject(Query.FieldByName('ID').AsString, Node);
Query.Next;
end;
finally
List.Free;
end;
finally
TreeView.Items.EndUpdate;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
T: DWORD;
begin
T := GetTickCount;
Query1.SQL.Text := 'SELECT * FROM FTree ORDER BY ParentID, ID';
Query1.Open;
MakeTree(Query1, TreeView1);
Label1.Caption := Format('MakeTree所用时间: %d ms', [GetTickCount - T]);
end;

生成一棵树方法二:

procedure CreateTree(DataSet: TADOQuery; Tree: TTreeView;
const table, aid, aname: string; idname: Boolean);
const
ID_DEPT = 2;
var
nLevel: Integer;
pNodes: array[0..1023] of TTreeNode;
lpID, lpName, s: string;
begin
if DataSet = nil then Exit;
if Tree = nil then Exit;
if table = '' then Exit;
pNodes[0] := nil;
Tree.Items.Clear;
with DataSet do
begin
Close;
SQL.Clear;
s := Format('select %s, %s from %s order by %s', [aid, aname, table, aid]);
SQL.Text := s;
Open;
if IsEmpty then Exit;
First;
while not Eof do
begin
lpID := FieldByName(aid).AsString;
lpName := FieldByName(aname).AsString;
nLevel := Length(lpID) div ID_DEPT;
if not idname then
pNodes[nLevel] := Tree.Items.AddChild(pNodes[nLevel - 1], lpName)
else
pNodes[nLevel] := Tree.Items.AddChild(pNodes[nLevel - 1],
lpID + '-' + lpName);
Next;
end;
end;
end;

遍历一棵树:
procedure TForm1.Button1Click(Sender: TObject);
var
node: ttreenode;
begin
node := treeview1.Items.GetFirstNode;
while node <> nil do
begin
node := node.GetNext;
end;
end;

  • 0
    点赞
  • 0
    收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值