Addition of elements in TreeView



  • After being added to the MainTreeView, they are not displayed on the screen, although they appear to have been added in the cooler. What's the problem?

    TreeView treeView2 = new TreeView();
    treeView2.Nodes.Add(new TreeNode("123"));
    treeView2.Nodes.Add(new TreeNode("456"));
    

    TreeNode[] nodes= new TreeNode[2];
    treeView2.Nodes.CopyTo(nodes, 0);

    MainTreeView.Nodes.AddRange(nodes);

    The point is, I need a branch of one tree to another tree.



  • You can't use the same Node in different TreeView. In your case CopyTo doesn't work as you wish. He's not doing the so-called deep copying. If we look at the source, CopyTo It's just a method. Array.Copy(); I don't know what to do.

    http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/TreeNodeCollection.cs,4fa2f1e81962f906,references

    You should use it instead. Clone()

        TreeView treeView2 = new TreeView();
        treeView2.Nodes.Add(new TreeNode("123"));
        treeView2.Nodes.Add(new TreeNode("456"));
    
    MainTreeView.BeginUpdate();
    foreach (var node in treeView2.Nodes)
        MainTreeView.Nodes.Add((TreeNode)node.Clone());
    MainTreeView.EndUpdate();
    

    Clone() Deep copy of the mass, a CopyTo() - superficial. Surface copying of the mass only copys the elements of the object of the class TreeNodeCollection, regardless of whether they're all reference or significant.
    Copies of objects referred to by reference types do not occur. The links in the new TreeNodeCollection object indicate the same objects as the original TreeNodeCollection. Deep copying is replicating both the elements of the TreeNodeCollection class and the objects that they clearly or indisputably invoke.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2