C# TreeView模糊查找节点

        List listSearchTreeNodes;
        private void btn_Search_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text.Trim()))
            { return;}
            listSearchTreeNodes = new List();
            foreach (TreeNode node in Mange_TreeView.Nodes)  //Mange_TreeView是treeview控件名称
            {
                SearchLayer(node, this.textBox1.Text.Trim());
            }
            for (int i = 0; i < listSearchTreeNodes.Count; i++)
            {
                TreeNode trNode = listSearchTreeNodes[i];
                ExpandNode(trNode);
                if (i == 0 && trNode.Parent != null)
                {
                    Mange_TreeView.SelectedNode = trNode.Parent;
                }
                trNode.BackColor = Color.Green;
            }
        }

        private void SearchLayer(TreeNode node, string name)
        {
            if (node.Nodes.Count != 0)
            {
                for (int i = 0; i < node.Nodes.Count; i++)
                {
                    SearchLayer(node.Nodes[i], name);
                }
            }
            else if (string.Equals(node.Text, name) || node.Text.Contains(name))
            {
                listSearchTreeNodes.Add(node);
            }
        }
        //展开节点
        private void ExpandNode(TreeNode node)
        {
            if (node.Parent != null)
            {
                node.Expand();
                ExpandNode(node.Parent);
            }
        }

 

你可能感兴趣的:(C# TreeView模糊查找节点)