finding and replacing a tree node in C#

后端 未结 1 1956
半阙折子戏
半阙折子戏 2021-01-29 00:06

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

相关标签:
1条回答
  • 2021-01-29 00:52

    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);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题