0

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.

1 Answer 1

3

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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?
I am using FrameWork 3.5 and I believe that on Framework 1.1 you can use Nodes See documentation msdn.microsoft.com/en-us/library/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.