Re: TreeView refresh and reselect by Jeff
Jeff
Wed Oct 20 11:58:16 CDT 2004
On 20/10/2004 Andreas Zita wrote:
> Hi all,
>
> I have a TreeView control which at times is updated (rebuilt) to
> reflect changes done by the user. However when this happens the
> currently selected node is of course deselected. How do a make a nice
> and professional solution that reselects the same node after update?
> (if it still exists). I notices that there is a property FullPath in
> the a TreeNode. But the TreeView doesnt seem to have a method like
> SelectByPath(). Any recomendations here?
>
> /ANdreas
If you re-build the TreeView completely then you can't go to a saved
node since it won't exist any more - as I expect you have discovered :-)
I 'rolled my own' as follows:
private bool TVSetToFullPath(string strFullPath, TreeNode tnStart, bool
blnExpandFinalNode)
{
// Sets the TreeView to the requested FullPath starting search from
tnStart
if(strFullPath == "")
return false;
int intCount;
string[] strNames = strFullPath.Split('\\');
int intLast = strNames.GetUpperBound(0);
TreeNode tnChild = tnStart;
tnChild.Expand();
for(intCount = 0; intCount <= intLast; intCount++)
{
tnChild = TVGetNodeFromName(strNames[intCount], tnChild);
if(tnChild != null)
{
if(intCount < intLast)
tnChild.Expand();
else
{
if(blnExpandFinalNode)
tnChild.Expand();
}
}
else
break;
}
if(tnChild != null)
{
tvMain.SelectedNode = tnChild;
return true;
}
else
{
return false;
}
}
private TreeNode TVGetNodeFromName(string strName, TreeNode tnTop)
{
TreeNode tnReturn = null;
if(tnTop.Text == strName)
return tnTop;
foreach(TreeNode tnChild in tnTop.Nodes)
{
if(tnChild.Text == strName)
{
tnReturn = tnChild;
break;
}
}
return tnReturn;
}
I'm open to better ideas though :-)
--
Jeff Gaines Damerham Hampshire UK