I have a treeview, which is populated with multiple nodes based on a directory structure, sometimes single, but often in parent-child-relationships.
My goal is to filter the treeview by keyword.
I accomplished this using
private void Filter()
{
TreeView tv = new TreeView();
//Clone backup List<TreeNode> myTreeview into temporary TreeView tv
foreach (TreeNode n in myTreeview)
tv.Nodes.Add((TreeNode)n.Clone());
treeViewInForm.Nodes.Clear();
if (txtKeyword.Text == "")
{
treeViewInForm.Nodes.AddRange(myTreeview.ToArray());
}
else
{
foreach (TreeNode n in tv.Nodes)
{
RecursiveFunction(n);
}
treeViewInForm.ExpandAll();
}
}
private void RecursiveFunction(TreeNode treeNode)
{
if (treeNode.Text.ToLower().Contains(txtKeyword.Text.ToLower()))
{
this.Invoke((MethodInvoker)delegate
{
TreeNode root = new TreeNode();
TreeNode node = root;
bool beginn = true;
foreach (string pathBits in treeNode.FullPath.Split('\\'))
{
//Comnsole.WriteLine("pb: " + pathBits);
if (beginn)
{
beginn = false;
node.Text = pathBits;
}
else
{
node = AddNode(node, pathBits);
}
}
treeViewInForm.Nodes.Add(root);
});
}
foreach (TreeNode tn in treeNode.Nodes)
{
RecursiveFunction(tn);
}
}
So let's say, the relationship is Example A
Node
Child(Contains Keyword)
ChildOfChild(Does or does not contain Keyword)
...
What I get is Example B
Node
Child(Contains Keyword)
or Example C, if ChildOfChild contains the keyword
Node
Child(Contains Keyword)
Node
Child(Contains Keyword)
ChildOfChild(Does contain Keyword)
How do I get Example A, collapsed up to the point of the first child(or parent) that contains the keyword?