Home > OS >  How to make copy of a treeview nodes to another treeview
How to make copy of a treeview nodes to another treeview

Time:10-28

How do I take the data from one populated treeview and put it into another existing treeview. All the nodes and children need to be copied.

CodePudding user response:

I think you can use a stream to save and load tree content. I don't have a running environment right now to test an example but, your code could looks like :

var
  MS: TMemoryStream;
begin
  MS := TMemoryStream.Create;
  try
    Tree1.SaveToStream(MS);
    MS.Position := 0;
    Tree2.LoadFromStream(MS);
  finally
    MS.Free;
  end;
end;

CodePudding user response:

TTreeNode implements the TPersistent.Assign() method, so one option would be to write a recursive function that iterates the source TreeView adding-and-assigning nodes to the target TreeView. For example:

procedure CopyNodes(SrcTree, DstTree: TTreeView);
var
  DstNodes: TTreeNodes;
  SrcRootNode: TTreeNode;

  procedure DoCopyNodes(SrcNode, Relative: TTreeNode; AddMode: TNodeAttachMode);
  var
    DstNode: TTreeNode;
  begin
    while SrcNode <> nil do
    begin
      DstNode := DstNodes.AddNode(nil, Relative, '', nil, AddMode);
      try
        DstNode.Assign(SrcNode);
        DoCopyNodes(SrcNode.GetFirstChild, DstNode, naAddChild);
      except
        DstNode.Delete;
        raise;
      end;
      SrcNode := SrcNode.GetNextSibling;    
    end;
  end;

begin
  SrcRootNode := SrcTree.Items.GetFirstNode;
  if SrcRootNode <> nil then
  begin
    DstNodes := DstTree.Items;
    DstNodes.BeginUpdate;
    try
      DoCopyNodes(SrcRootNode, nil, naAdd);
    finally
      DstNodes.EndUpdate;
    end;
  end;
end;
CopyNodes(TreeView1, TreeView2);
  • Related