如何删除未选择的树视图节点

时间:2018-01-18 06:49:08

标签: c# treeview

如何删除未选择的树视图节点。即使i循环两次仍然需要在删除所有未选择的treenode之前单击按钮三次。 这就是:

    private void buttonShowSelected_Click(object sender, EventArgs e)
            { 
                for (int i = 0; i < treeViewFilter.Nodes.Count; i++)
                {
                    DeleteUnselectedNodes();               
                }
            }


 private void DeleteUnselectedNodes()
 {
     for (int i = 0; i < treeViewFilter.Nodes.Count; i++)
     {
         TreeNode aNode = treeViewFilter.Nodes[i];
         treeViewFilter.SelectedNode = aNode.FirstNode;

         if (!aNode.Checked)
         {
             treeViewFilter.Nodes.Remove(aNode);
         }
     }
 }

2 个答案:

答案 0 :(得分:1)

您的循环不会检查任何子节点。递归函数或堆栈可以工作:

var nodes = new Stack<TreeNode>(treeViewFilter.Nodes.Cast<TreeNode>());
while (nodes.Count > 0) {
  var n = nodes.Pop();
  if (!n.Checked) {
    if (n.Parent != null) {
      n.Parent.Nodes.Remove(n);
    } else {
      treeViewFilter.Nodes.Remove(n);
    }
  } else {
    foreach (TreeNode tn in n.Nodes) {
      nodes.Push(tn);
    }
  }
}

答案 1 :(得分:0)

你应该递归地走树;

private void buttonShowSelected_Click(object sender, EventArgs e)
{
    var nodes = new List<TreeNode>(treeViewFilter.Nodes.Cast<TreeNode>());
    foreach (var treeNode in nodes)
    {
        DeleteUnselectedNodes(treeNode);
    }
}

private void DeleteUnselectedNodes(TreeNode node)
{
    var nodes = new List<TreeNode>(node.Nodes.Cast<TreeNode>());
    foreach (var treeNode in nodes)
    {
        DeleteUnselectedNodes(treeNode);
    }

    if (!node.Checked)
    {
        var parent = node.Parent;
        if (parent != null) //If it isn't root
        {
            parent.Nodes.Remove(node);
        }
        else
        {
            treeViewFilter.Nodes.Remove(node);
        }
    }
}