在Winform中的TreeView控件,实现选中/取消选中父节点则自动选择/取消选中对应子节点

用两个递归来设置子节点和父节点的状态,如下

private void CheckChild(TreeNode node)
        {
            if (node.Nodes.Count != 0)
            {
                foreach (TreeNode item in node.Nodes)
                {
                    item.Checked = node.Checked;
                    CheckChild(item);
                }
            }
        }
        private void CheckParent(TreeNode node)
        {
            if (node.Parent != null)
            {
                int count = 0;
                foreach (TreeNode item in node.Parent.Nodes)
                {
                    if (item.Checked)
                    {
                        count++;
                    }
                }
                node.Parent.Checked = (count == node.Parent.Nodes.Count);
                CheckParent(node.Parent);
            }
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            CheckChild(e.Node);
            CheckParent(e.Node);
        }
posted @ 2011-04-07 21:40  V587  阅读(863)  评论(0编辑  收藏  举报