Search code examples
c#winformstreeviewtreenode

Search TreeNodes in a TreeView


I have a TreeView containing some TreeNode, as presented below:

TreeView with text box

My idea is to use the textBox1 as a search engine to show only the TreeNodes that are containing the text of textBox1. I already have a function that can parse the different nodes and look if the text contained in textBox1 is contained of each node:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    foreach (var node in Collect(treeView1.Nodes))
    {
        if (node.Text.ToLower().Contains(textBox1.Text.ToLower()))
        {
            //I want to show those nodes 
            Debug.Write("Contained : ");
            Debug.WriteLine(node.Text);
        }
        else
        {
            //I want to hide those nodes
            Debug.Write("Not contained : ");
            Debug.WriteLine(node.Text);
        }
    }
}

As the property isVisible for TreeNode is only a getter, how to hide the TreeNodes that do not contain the searched text?


Solution

  • From the documantation there is no way to hide treenode. But instead you can remove and re-add that node. You can do this with the below approach:

    public class RootNode : TreeNode
    {
        public List<ChildNode> ChildNodes { get; set; }
    
        public RootNode()
        {
            ChildNodes = new List<ChildNode>();
        }
    
        public void PopulateChildren()
        {
            this.Nodes.Clear();
    
            var visibleNodes = 
                ChildNodes
                .Where(x => x.Visible)
                .ToArray();
    
            this.Nodes.AddRange(visibleNodes);
        }
    
        //you would use this instead of (Nodes.Add)
        public void AddNode(ChildNode node)
        {
            if (!ChildNodes.Contains(node))
            {
                node.ParentNode = this;
                ChildNodes.Add(node);
                PopulateChildren();
            }
        }
    
        //you would use this instead of (Nodes.Remove)
        public void RemoveNode(ChildNode node)
        {
            if (ChildNodes.Contains(node))
            {
                node.ParentNode = null;
                ChildNodes.Remove(node);
                PopulateChildren();
            }
    
        }
    }
    
    public class ChildNode : TreeNode
    {
        public RootNode ParentNode { get; set; }
        private bool visible;
        public bool Visible { get { return visible; } set { visible = value;OnVisibleChanged(): } }
        private void OnVisibleChanged()
        {
            if (ParentNode != null)
            {
                ParentNode.PopulateChildren();
            }
        }
    }