你应该对 TreeViews 使用递归方法,所以试试这个工作正常:
...
foreach (TreeNode item in treeView1.Nodes)//in case you have multiple rootnodes
treeView2.Nodes.Add((TreeNode)item.Clone());//clone all treeview1 nodes into treeview2
foreach (TreeNode node in treeView2.Nodes)//in case you have multiple rootnodes
AmISelected(node, "momo");//filter all nodes recursively
...
和
private bool AmISelected(TreeNode root, string myString)
{
bool bfound = false;
if (root.Text == myString)
bfound = true;// I do have myString
for (int i = root.Nodes.Count - 1; i >= 0; i--)
if (AmISelected(root.Nodes[i], myString))
bfound = true;// I've a child who have myString
if (!bfound) //if i don't have myString neither any of my children
if (root.Parent == null) // is it a root node
treeView2.Nodes.Remove(root);
else
root.Parent.Nodes.Remove(root);
return bfound;
}