C# – Filter a Treeview with a Textbox in a C# winforms app

cfiltertreeviewwinforms

I have a TreeView in my a C# winform. I would like to be able to add a search functionality through a search box.
Basically as the user types in letters (I'm guessing on the _TextChanged event), I show only the nodes that contain childnodes with the inputed letters…

My TreeView contains 53 parent nodes for a total of over 15000 Nodes so I need something a bit performant. I build my TreeView from a csv that I load into a DataTable and then make queries on to get the Parent nodes with associated child nodes…

UPDATE

I have an idea.
The final aim is that when a user doubleclicks on a child node it gets added to a listView.

I had first implemented this search function in a simple list view where I didn't separate my data into categories.

My idea is that once the user starts typing in things, I turn off my Tree view and show the list view instead…

I'll try and implement and see what it gives performance wise… Any critics on this idea are welcome.

Best Answer

Finally this is what I did, it suits my requirements. I first make a copy of my TreeView and store into fieldsTreeCache. I then clear the fieldsTree. I then search through the cache and add any node containing my search parameter to the fieldsTree. Note here that once you search, you no longer have the parent nodes that show. You just get all of the end nodes. I did this because if not I had 2 choices:

  • Expand all the parent nodes containing childs that match but then it was slow and one parent might have 50 children which isn't great visually.
  • Not expand the parent nodes but then you just get the categories and not the children nodes that you're searching for.

    void fieldFilterTxtBx_TextChanged(object sender, EventArgs e)
    {
        //blocks repainting tree till all objects loaded
        this.fieldsTree.BeginUpdate();
        this.fieldsTree.Nodes.Clear();
        if (this.fieldFilterTxtBx.Text != string.Empty)
        {
            foreach (TreeNode _parentNode in _fieldsTreeCache.Nodes)
            {
                foreach (TreeNode _childNode in _parentNode.Nodes)
                {
                    if (_childNode.Text.StartsWith(this.fieldFilterTxtBx.Text))
                    {
                        this.fieldsTree.Nodes.Add((TreeNode)_childNode.Clone());
                    }
                }
            }
        }
        else
        {
            foreach (TreeNode _node in this._fieldsTreeCache.Nodes)
            {
                fieldsTree.Nodes.Add((TreeNode)_node.Clone());
            }
        }
        //enables redrawing tree after all objects have been added
        this.fieldsTree.EndUpdate();
    }
    
Related Topic