树的一些操作

生成一棵树方法一:
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;

posted @ 2012-07-26 12:44  delphi中间件  阅读(373)  评论(0编辑  收藏  举报