C# Treeview checking if node exists

前端 未结 8 726
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 12:42

I\'m trying to populate a treeview from an XmlDocument. The Root of the tree is set as \'Scripts\' and from the root the next level should be \'Departments\' which is within the

8条回答
  •  無奈伤痛
    2021-01-23 13:05

    if(treeView1.Nodes.ContainsKey("DEPARTMENT")){
    //...
    }
    

    EDIT: Recursive method:

     bool exists = false;
            foreach (TreeNode node in treeView1.Nodes) {
                if (NodeExists(node, "DEPARTMENT"))
                    exists = true;
            }
        private bool NodeExists(TreeNode node, string key) {
            foreach (TreeNode subNode in node.Nodes) {
                if (subNode.Text == key) {
                    return true;
                }
                if (node.Nodes.Count > 0) {
                    NodeExists(node, key);
                }
            }
            return false;
        }
    

提交回复
热议问题