摘自:
一个表,三个字段
Id : 结点的ID整型的
ParentId : 父结点的ID,没有父结点则为0
Name : 结点的文本。
{ 装入目录 }
procedure TMainForm.LoadFolder;
function GetParentNode(Id: integer): TTreeNode;
var
i iCount:integer;
begin
result := nil;
with TreeView do
begin
iCount := Items.Count - 1;
for i := iCount downto 0 do
if integer(Items[i].Data) = Id then
begin
result := Items[i];
break;
end;
end;
end;
var
i iCount: integer;
iFolderId iParentId: integer;
sFolderName: string;
begin
with tblFolder TreeView1 do
begin
iCount := RecordCount;
Items.BeginUpdate;
Items.Clear;
for i := 1 to iCount do
begin
RecNo := i;
iFolderId := FieldByName( 'Id ').AsInteger;
iParentId := FieldByName( 'ParentId ').AsInteger;
sFolderName := FieldByName( 'Name ').AsString;
Items.AddChild(GetParentNode(iParentId) sFolderName);
Items[i - 1].Data := Pointer(iFolderId);
end;
Items.EndUpdate;
end;
end;
{ 重新保存TreeView中的索引 }
procedure TMainForm.ReSaveFolderIndex;
var
i iCount: integer;
begin
with tblFolder TreeView1 do
begin
iCount := RecordCount;
for i := 0 to iCount - 1 do
begin
RecNo := i + 1;
Edit;
FieldByName( 'Id ').AsInteger := integer(Items[i].Data);
FieldByName( 'Name ').AsString := Items[i].Text;
if Items[i].Parent = nil then
FieldByName( 'ParentId ').AsInteger := 0
else
FieldByName( 'ParentId ').AsInteger := integer(Items[i].Parent.Data);
Post;
end;
end;
end;
//当你新增、移动、删除结点时执行过程ReSaveFolderIndex;
摘自:
Delphi(Pascal) code
type TMyData = record //申明一个自定义类型 用于存放Data数据 ID: String; //这里可以多个记录域 可以不仅仅只有ID end; PMyData = ^TMyData; var MyData : PMyData; begin ...... new(MyData); MyData^.ID := ADOQuery2.FieldByName('CP_ID').AsString; //注: MyData^.ID可以省略写成MyData.ID myNodeChild.Data := MyData; ...... end;
另外 要在TreeView组件的OnDeletion事件中加上以下代码 以释放Data数据所占的空间:
Delphi(Pascal) code
procedure TForm1.TreeView1Deletion(Sender: Tobject; Node: TTreeNode); begin if Node.Data nil then begin Dispose(Node.Data); Node.Data := nil; end; end