C# Treeview 检查节点是否存在 [英] C# Treeview checking if node exists

查看:62
本文介绍了C# Treeview 检查节点是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 XmlDocument 填充树视图.树的根设置为脚本",从根开始,下一级应该是 XML 脚本中的部门".我可以从 XML 文档中获取数据没问题.我的问题是当循环遍历 XmlDocument 并将节点添加到根节点时,我想确保如果某个部门已经在树视图中,则不会再次添加它.我还应该补充一点,每个部门还有一个脚本列表,这些脚本需要成为部门的子节点.

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 XML script. I can get data from the XML document no problem. My question is when looping through the XmlDocument and adding nodes to the root node, I want to ensure that if a department is already within the treeview then it is not added again. I should also add that each Department also has a list of scripts that need to be child nodes of the department.

到目前为止我的代码是:

My code so far is:

        XmlDocument xDoc = new XmlDocument();
        xDoc.LoadXml(scriptInformation);
        TreeNode t1;
        TreeNode rootNode = new TreeNode("Script View");
        treeView1.Nodes.Add(rootNode);
        foreach (XmlNode node in xDoc.SelectNodes("//row"))
        {
            t1 = new TreeNode(node["DEPARTMENT"].InnerXml);
           //How to check if node already exists in treeview?



        }

谢谢.

推荐答案

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

递归方法:

 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;
    }

这篇关于C# Treeview 检查节点是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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