在 C# 中带有复选框的 TreeView [英] TreeView with CheckBoxes in c#

查看:48
本文介绍了在 C# 中带有复选框的 TreeView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 c# 中有一个带有复选框的树视图,我希望当用户检查一个节点时,自动检查以下级别上的所有节点.有没有人知道如何做到这一点,而无需在用户每次检查某个节点时在所有树上运行可恢复函数?

I have a tree view with checkboxes in c#, I want that when the user checks one node all the nodes that there are on the levels below automatic checked also. Does anyone know about way to do that without run with recorsive fnction on all the tree each time that the user checks some node?

谢谢

//此函数返回树视图.

//this function returns the 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# 中带有复选框的 TreeView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆