Copy treeNodeCollection problem
-
hi. how can copy all nodes of a treeview in another at once? i dont want to use foreach methode.
sepel
foreach (Node ndSource in treeSource.Nodes)
{
Node newNode = new Node();
newNode.Text = ndSource.Text;
-- copy all required properties like the text property above --
ChildNodes(ndSource, newNode);
treeDestination.Nodes.Add(newNode);
}private void ChildNodes(Node ParentNode, Node newParent)
{
foreach (Node ndChild in ParentNode.Nodes)
{
Node newNode = new Node();
newNode.Text = ndChild.Text;
-- copy all required properties like the text property above --
ChildNodes(ndChild);
newParent.Nodes.Add(newNode);
}
}.: I love it when a plan comes together :. http://www.zonderpunt.nl
-
hi. how can copy all nodes of a treeview in another at once? i dont want to use foreach methode.
sepel
A node can't exist in two treevies at once. Each node has to be cloned first so some sort of loop is inevitable. Two code snippets below. The first does what you want but with a loop. The second moves the nodes rather than copies but no loop required.
// Copies the nodes
if (treeView1.Nodes.Count > 0)
{
TreeNodeCollection treeNodes = treeView1.Nodes;
TreeNode[] nodearray = new TreeNode[treeNodes.Count];
for (int i = 0; i < nodearray.Length; i++)
{
nodearray[i] = (TreeNode)treeNodes[i].Clone();
}
treeView2.Nodes.AddRange(nodearray);
}//Moves the nodes
if (treeView1.Nodes.Count > 0)
{
TreeNodeCollection treeNodes = treeView1.Nodes;
TreeNode[] nodearray = new TreeNode[treeNodes.Count];
treeNodes.CopyTo(nodearray, 0);
//Clear the original tree as nodes can't exist in both
treeView1.Nodes.Clear();
treeView2.Nodes.AddRange(nodearray);
}Dave
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia) -
A node can't exist in two treevies at once. Each node has to be cloned first so some sort of loop is inevitable. Two code snippets below. The first does what you want but with a loop. The second moves the nodes rather than copies but no loop required.
// Copies the nodes
if (treeView1.Nodes.Count > 0)
{
TreeNodeCollection treeNodes = treeView1.Nodes;
TreeNode[] nodearray = new TreeNode[treeNodes.Count];
for (int i = 0; i < nodearray.Length; i++)
{
nodearray[i] = (TreeNode)treeNodes[i].Clone();
}
treeView2.Nodes.AddRange(nodearray);
}//Moves the nodes
if (treeView1.Nodes.Count > 0)
{
TreeNodeCollection treeNodes = treeView1.Nodes;
TreeNode[] nodearray = new TreeNode[treeNodes.Count];
treeNodes.CopyTo(nodearray, 0);
//Clear the original tree as nodes can't exist in both
treeView1.Nodes.Clear();
treeView2.Nodes.AddRange(nodearray);
}Dave
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)