本帖最后由 yangjinan0729 于 2010-09-18 16:32:43 编辑

解决方案 »

  1.   

    try
    private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
    {
        //只捕获checkbox操作事件
        if (e.Action != TreeViewAction.Unknown)
        {
            bool all_selected = true;
            foreach (TreeNode node in e.Node.Parent.Nodes)
            {
                if (!node.Checked)
                {
                    all_selected = false;
                    break;   
                }
            }
            TreeNode p = e.Node.Parent;
            while (p!= null)
            {
                p.Checked = all_selected;
                p = p.Parent;
            }
        }
    }
      

  2.   

    哎 这样就可以了  今天下午脑子有问题了
     //处理TreeView1的checkbox事件
            private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
            {
                //只捕获checkbox操作事件
                if (e.Action != TreeViewAction.Unknown)
                {
                    tree(e.Node);
                }
            }
            private void tree(TreeNode tn)
            {
                if (tn.Parent != null)
                {
                    //节点未选中,则设置祖先节点为false
                    if (tn.Checked == false)
                    {
                        tn.Parent.Checked = false;
                        if (tn.Parent.Parent != null)
                        { 
                            //tn.Parent.Parent.Checked = false; 
                            tree(tn.Parent);
                        }
                    }
                    else if (tn.Checked)
                    {
                        if (tn.Nodes.Count > 0)
                        {
                            this.CheckAllChildNodes(tn, tn.Checked);
                        }
                    }
                    //指示是否全部选中了节点的子节点,如果子节点全部选中之后则自动选中此父节点
                    bool ischecked = true;
                    foreach (TreeNode ctn in tn.Parent.Nodes)
                    {
                        ischecked = ischecked & ctn.Checked;
                    }
                    if (ischecked)
                    {
                        tn.Parent.Checked = true;
                        if (tn.Parent.Parent != null)
                        {
                            tree(tn.Parent);
                        }
                        //tree(e.Node.Parent);
                    }
                }
            }        private void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked)
            {
                foreach (TreeNode node in treeNode.Nodes)
                {
                    node.Checked = nodeChecked;
                    if (node.Nodes.Count > 0)
                    {
                        // If the current node has child nodes, call the CheckAllChildsNodes method recursively.
                        this.CheckAllChildNodes(node, nodeChecked);
                    }
                }
            }