在 C# 中查找和替换树节点 [英] finding and replacing a tree node in C#

查看:55
本文介绍了在 C# 中查找和替换树节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 C# 代码中有一个树视图.我想在单击按钮时在整个树视图中用不同的文本替换树节点的所有现有出现.

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.

例如,我有 3 次出现文本"为手动"的节点.我想用文本自动"替换所有这 3 个节点.问题是这 3 个节点位于树视图中的 3 个不同分支下.它们不共享同一个父节点.我打算通过编写 for 循环来使这个过程自动化,但我不明白如何首先找到所需的 3 个节点.

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.

推荐答案

我建议使用递归.

当然,这是一个示例,您需要删除 myTree 声明并使用您的树,但这应该可以帮助您入门.

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);
        }
    }
}

这篇关于在 C# 中查找和替换树节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆