Well working with tree views would have been much easier if there was a way of locating the nodes based on their paths. I've searched around a bit from time to time but surprisingly there is no such method or function or a way with which you could do that. Or should I say- I couldnât find anything significant in this regard.
So here's a step, a function that would locate the nodes based on the paths provided
TreeNode LocateNode(string Path, TreeNodeCollection TreeCol)
{
string[] PTms = Path.Split(new Char[] {'\\'});
for(int k = 0; k < TreeCol.Count;k++)
{
if(TreeCol[k].Text == PTms[0])
{
if(TreeCol[k].Nodes.Count == 0 || PTms.Length == 1)
return TreeCol[k];
return LocateNode(Path.Remove(0,PTms[0].Length+1), TreeCol[k].Nodes);
}
}
return null;
}
I wrote this function to accept TreeNodeCollection, it was easier to write a recursive function that way, so you have to pass it the relevant TreeView's Nodes property.
Now what you can do is - save the FullPath property of the currently selected node. Once you are done with the adding, locate the node in the new tree with the saved FullPath, set it to the SelectedNode property of the TreeView.
That is case one.
Case Two would be if the contents of the tree are changing a bit too much or in such a way that u can no longer trust FullPath for leading you to the right node, in which case you will have to create and maintain the path separately for the node you want selected post insertion while the insertion process is on.
Once addition is over, use this path to locate the TreeNode and set it to the SelectedNode property.
I hope you find something useful out of it.
Disclaimer: This function is provided as is. I do not hold any guarantees if anything gets messed up using this function.
Donât get me wrong but U have to write such stuff.
Regards
Ankur Verma
|