我在C#中有一个带有复选框的树状 View ,我希望当用户检查一个节点时,也将自动检查以下级别上的所有节点也包括在内。
有人知道每次用户检查某个节点时都无需在所有树上运行具有协调功能的方法吗?

谢谢

//此函数返回treeView。

   public TreeView GetTreeView()
    {

        getSubject();
        // fill the treeview with all subjects.
        foreach (Subject subject in subjects)
        {
            //for each root subject fill all the his children.
            if (subject.subjestId == subject.parentSubject)
            {
                TreeNode node = new TreeNode(subject.subjectString, subject.subjestId, subject.subjestId);
                addChild(node, subject.subjestId);
                tv.Nodes.Add(node);
            }
        }
        return tv;
    }
   // for each subject return sub subjects.
   private void addChild(TreeNode node, int parentId)
    {
        foreach (Subject subject in subjects)
        {
            if (subject.parentSubject == parentId && subject.parentSubject != subject.subjestId)
            {
                TreeNode childNode = new TreeNode(subject.subjectString, subject.subjestId, subject.subjestId);
                addChild(childNode, subject.subjestId);
                node.Nodes.Add(childNode);
            }
        }
    }

最佳答案

递归。像这样:

    bool busy = false;

    private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) {
        if (busy) return;
        busy = true;
        try {
            checkNodes(e.Node, e.Node.Checked);
        }
        finally {
            busy = false;
        }
    }

    private void checkNodes(TreeNode node, bool check) {
        foreach (TreeNode child in node.Nodes) {
            child.Checked = check;
            checkNodes(child, check);
        }

关于c# - 在 C# 中带有复选框的 TreeView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5478984/

10-15 17:25