public TreeNode GetNodeFromPath(TreeNode node, string path)
{
TreeNode foundNode = null;
foreach (TreeNode tn in node.Nodes)
{
if (tn.FullPath == path)
{
return tn;
}
else if (tn.Nodes.Count > 0)
{
foundNode = GetNodeFromPath(tn, path);
}
if (foundNode != null)
return foundNode;
}
return null;
}
Too bad there's no built-in function from Microsoft, could have been a bit quicker than a recursive tree search....
ReplyDeleteIf there are two or more elements with the same name at the same level in the tree, this will return the first of the elements....
ReplyDeleteI guess that's a limitation. Any suggestions are welcome.
ReplyDeleteHave a look at this one:
ReplyDeletehttp://pradeep1210.spaces.live.com/Blog/cns!2E84C99518D46BB4!258.entry
//I guess this is what you are searching for:
ReplyDelete// search recursively
private TreeNode FindNode(TreeNodeCollection tncoll, String strText)
{
TreeNode tnFound;
foreach (TreeNode tnCurr in tncoll)
{
if (tnCurr.FullPath == strText)
{
return tnCurr;
}
tnFound = FindNode(tnCurr.Nodes, strText);
if (tnFound != null)
{
return tnFound;
}
}
return null;
}
// call it with
private void Button1_Click(object sender, EventArgs e)
{
tv_categories.SelectedNode = FindNode(tv_categories.Nodes, @"Full\Path");
}
Thank you very much!
ReplyDeleteadding TreeView nodes in Windows Forms
ReplyDelete