JohnsonGuo的方法是可以的。
如果你想每个节点保存为一条纪录,或你想保存TreeNode.Data中的附加
信息。你就要对树进行遍历。(这是我以前做过的东西,有一些无关的东
西我删掉了,比如对TreeNode.Data的保存,所以显得有些罗嗦)
procedure SaveTreeToDB(STree: TTreeview; TreeDB: TTable);
var
i: Integer;
ANode: TTreeNode;
begin
with TreeDB do
begin
ExEmptyTable(TreeDB);//这是清空以前数据的函数,你可以自己写
if not Active then Open;
if Assigned(STree) then
try
with STree.Items do
if Count > 0 then
begin
ANode := GetFirstNode;
while ANode<> nil do
begin
Append;
FieldByName('ID').AsInteger := GetUniqueNo;//产生唯一号的函数
FieldByName('Level').AsInteger:=ANode.Level;
FieldByName('Text').AsString:=ANode.Text;
Post;
ANode := ANode.GetNext;
end;
end;
finally
Close;
end;
end;
end;
procedure LoadTreeFromDB(STree: TTreeview; TreeDB : TTable);
var
ANode, NextNode: TTreeNode;
ALevel: Integer;
CurrStr: string;
begin
with STree.Items do
begin
BeginUpdate;
try
try
Clear;
if not TreeDB.Active then TreeDB.Open;
TreeDB.First;
ANode := nil;
while not TreeDB.Eof do
begin
Level:= TreeDB.FieldByName('Level').AsInteger;
CurrStr:= TreeDB.FieldByName('Text').AsInteger;
if ANode = nil then
ANode:= AddChild(nil, CurrStr);
else if ANode.Level = ALevel then
ANode:= AddChild(ANode.Parent, CurrStr);
else if ANode.Level = (ALevel - 1) then
ANode := AddChild(ANode, CurrStr);
else if ANode.Level > ALevel then
begin
NextNode := ANode.Parent;
while NextNode.Level > ALevel do
NextNode := NextNode.Parent;
ANode := AddChild(NextNode.Parent, CurrStr);
end;
TreeDB.Next;
end;
finally
EndUpdate;
TreeDB.Close;
end;
except
Owner.Invalidate; // force repaint on exception
raise;
end;
end;
end;