TreeView refresh and reselect

  • Thread starter Thread starter Andreas Zita
  • Start date Start date
A

Andreas Zita

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
 
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 :-)
 
Back
Top