Copy tree and set new database id's
I'm trying to copy a tree. The tree is saved in an SQLite database and I load this into a treeview. The table structure is like: id,parent,level,position. In the treeview the id is given to the node object. Now I want to copy the tree recursively. It is necessary to generate new id's and set the parent id's correct:
procedure copyTree(machineId, parent : integer; startNode : TTreeNode);
var
tmpId : integer;
tmpData : TAssignmentData; // Record
begin
if assigned(startNode) then
begin
//Read out data from existing node
tmpData := data.getAssignment(integer(startnode.Data));
//Set node data to new machine
tmpData.machine := machineId;
//If node is on the top level
if tmpData.parent <> 0 then
tmpData.parent := parent;
//Write dataset (new node) to the database
tmpId := data.insertAssignment(tmpData);
copyTree(machineId, tmpId, startnode.getFirstChild);
copyTree(machin开发者_StackOverflow中文版eId, tmpId, startnode.getNextSibling);
end;
end;
I've tried this code, but the parent id's are not set correct in the database. The assignment is lost. Where is my mistake?
Best regards ...
Assuming data.insertAssignment(tmpData);
returns the new id for a node then only that node's children should have their parent id set to tmpId. You are setting the next sibling's parentid to tmpId as well!
copyTree(machineId, tmpId, startnode.getNextSibling);
Consider just passing parent for sibling nodes:
copyTree(machineId, parent, startnode.getNextSibling);
精彩评论