tags:

views:

345

answers:

1

I have a treeview in my C# code. I want to replace all existing occurences of a tree node with a different text in my entire treeview upon a button click.

For Example, I have 3 occurences of a node with 'Text' as "Manual". I want to replace all of these 3 nodes with the text "Automatic". The problem is that these 3 nodes are under 3 different branches in the treeview. They do not share the same parent node. I intend to write to make this process automatic by writing a for loop but I dont understand how to find the required 3 nodes in the first place.

+2  A: 

I would suggest using recursivity.

Of course this is an exemple and you would need to remove the myTree declaration and use your tree but this should get you started.

private void replaceInTreeView()
{
    TreeView myTree = new TreeView();
    ReplaceTextInAllNodes(myTree.Nodes, "REPLACEME", "WITHME");
}

private void ReplaceTextInAllNodes(TreeNodeCollection treeNodes, string textToReplace, string newText)
{
    foreach(TreeNode aNode in treeNodes)
    {
        aNode.Text = aNode.Text.Replace(textToReplace, newText);

        if(aNode.ChildNodes.Count > 0)
            ReplaceTextInAllNodes(aNode.ChildNodes, textToReplace, newText);
        }
    }
}
Philippe Asselin
It gives an error for aNode.ChildNodes.Count:'System.Windows.Forms.TreeNode' does not contain a definition for 'ChildNodes'What version of C# are you using?
VP
I am using FrameWork 3.5 and I believe that on Framework 1.1 you can use Nodes See documentation http://msdn.microsoft.com/en-us/library/system.windows.forms.treenode_members(VS.71).aspx
Philippe Asselin