Valhalla Legends Archive

Programming => General Programming => Topic started by: Noodlez on November 07, 2007, 12:44 AM

Title: Another C# Q
Post by: Noodlez on November 07, 2007, 12:44 AM
I have some nodes in a TreeView...I populate them.
After they're all populated I add another node, "Offline." I need to move every item under the other Nodes into my final Offline node. Any suggestions?
Title: Re: Another C# Q
Post by: MyndFyre on November 07, 2007, 03:28 AM
Iterate over them, remove them from their parents, and set their new parents to the offline node?

Really shouldn't be terribly difficult....
Title: Re: Another C# Q
Post by: Noodlez on November 07, 2007, 03:00 PM
Parent is a read only property
Title: Re: Another C# Q
Post by: Noodlez on November 07, 2007, 03:28 PM
It's ok, I did the iteration Remove and Insert loop.
Title: Re: Another C# Q
Post by: MyndFyre on November 07, 2007, 03:29 PM
Quote from: Noodlez on November 07, 2007, 03:00 PM
Parent is a read only property
Assuming:
Root
- Buddies
--MyndFyre
--Noodlez
-Co-workers
--Justin
--Ryan
--Jeff
--Steve
-Offline

int currentIndex = 0;
TreeNode offlineNode = whatever; // you need to have a reference to the offline node for the following code to work
// this code also assumes that you have one root node.  You'll have to adapt it for multiple.
while (currentIndex < rootNode.ChildNodes.Count)
{
 TreeNode currentNode = rootNode.ChildNodes[currentIndex];
 if (currentNode != offlineNode)
 {
   rootNode.ChildNodes.Remove(currentNode);
   offlineNode.ChildNodes.Add(currentNode);
 }
 else
 {
   currentIndex++;
 }
}


You can't use a foreach because you're going to change the collection you're iterating over while you're looping, so you have to use a for, while, or do-while.  A for loop is inappropriate because you don't necessarily want to increment each time.