TreeView根据路径得到选择节点

做~自己de王妃 提交于 2020-02-21 13:11:51

        /// <summary>
        /// 根据路径得到选择节点
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="treeView">树</param>
        /// <returns>节点</returns>
        private TreeNode GetNodeByPath(string path, TreeView treeView)
        {
            TreeNode node = new TreeNode();
            string[] pathLevel = path.Split('\\');

            int i = 0;
            foreach (TreeNode topNode in treeView.Nodes)
            {
                if (topNode.Text == pathLevel[i].ToString())
                {
                    node = topNode;
                    i++;
                    break;
                }
            }

            if (i < pathLevel.Length)
            {
                node = GetSubNode(node, pathLevel, i);
            }

     
            return node;
        }

        private TreeNode GetSubNode(TreeNode node, string[] pathLevel, int i)
        {
            TreeNode newNode = new TreeNode();
            foreach (TreeNode subNode in node.Nodes)
            {
                if (subNode.Text == pathLevel[i].ToString())
                {
                    newNode = subNode;
                    i++;
                    if (i == pathLevel.Length)
                    {
                        break;
                    }

                    if (i < pathLevel.Length)
                    {
                        newNode = GetSubNode(newNode, pathLevel, i);
                    }
                }
            }
            return newNode;

        }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!