遍历treeView子节点 同时遍历父结点 直到顶级结点 并不是全部父的集合

private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
  {
    oMM.ToggleAllChildNodes(e.Node,e.Node.Checked);
    treeView1.AfterCheck-=new TreeViewEventHandler(treeView1_AfterCheck);
    oMM.ToggleAllParentNodes(e.Node,e.Node.Checked);
    treeView1.AfterCheck+=new TreeViewEventHandler(treeView1_AfterCheck);
    //遍历父结点 时取消事件以免无限循环    
  }

 

public void ToggleAllChildNodes(TreeNode CurrentNode ,bool NodeChecked)
  {
   
    foreach(TreeNode node in CurrentNode.Nodes)
    {
     node.Checked=NodeChecked;
     if(node.Nodes.Count>0)
      this.ToggleAllChildNodes(node,NodeChecked);
    }
  }

  public void ToggleAllParentNodes(TreeNode CurrentNode ,bool NodeChecked)
  {
   if(NodeChecked)
   {
    CurrentNode.Checked=NodeChecked;
    if(CurrentNode.Parent!=null)
    {
      this.ToggleAllParentNodes(CurrentNode.Parent,NodeChecked);
    }

   }
  }

你可能感兴趣的:(treeview)