G'day,
What's your Search String? ie what are you passing to FindNode?
Here's some code I wrote to initialise a TreeView by location (think full path in Windows Explorer). (This is assuming your TreeView is already loaded).
Root
- Location
- <Location Code>
In the above example location would be 'Root\Location\<Location Code>'. In order to initialise the tree above using the code below, you'd make the call
SelectNode(MyTreeView, 'Root\Location\<Location Code>', '\');
I'm not saying the code below is elegant, but it gets the job done :-)
You'll see I'm calling ExpandNode. That's not normally required. For one of my uses of the below code it was a TShellTreeView I was initialising - and the child nodes are not pre-loaded by default (to speed the initial loading of the tree). the Child Nodes in TShellTreeView, which are folders in your filesystem are only loaded as required.
If this is your first time writing recursion, let me know if you have problems reading the code and I'll tighten and comment the code more. Recursion is great for trees, but it doesn't lead to linear code :-( the first call into the Recursive routine is on about the fifth last time of the entire block!
And forgive my hungarian notation - apparently this makes me old school nowadays :-)
And apparently FindNode replaces the need for FirstChild/GetNextSibling. It's either newer than Delphi 5, or I didn't know of it's existence in Delphi 5 :-)
Function SelectNode(oTree: TCustomTreeView; sLocation, sDelimiter: String): Boolean;
Function SelectNode2(oNode: TTreeNode; sRemainingLocation: String): Boolean;
Var
sNode: String;
oTemp: TTreeNode;
bLast: Boolean;
Begin
If Assigned(oNode) Then
Begin
oNode.Expand(False);
bLast := (Pos(sDelimiter, sRemainingLocation) = 0);
If Not bLast Then
sNode := TextBetween(sRemainingLocation, '', sDelimiter)
Else
sNode := sRemainingLocation;
oTemp := oNode.FindNode(sNode);
If Assigned(oTemp) Then
Begin
oTemp.Selected := True;
oTemp.MakeVisible;
If bLast Then
Result := True
Else
Result := SelectNode2(oTemp, TextBetween(sRemainingLocation, sDelimiter, ''));
End
Else
Result := False;
End
Else
Result := False;
End;
Var
oNode: TTreeNode;
sNode: String;
Begin
// Good ol' recursion - it's been a while...
oNode := oTree.TopItem;
If Assigned(oNode) Then
Begin
While Assigned(oNode.GetPrev) Do
oNode := oNode.GetPrev;
// We'll manually locate the first node ourselves.
If Copy(sLocation, 1, Length(sDelimiter)) = sDelimiter Then
sLocation := Copy(sLocation, 2, Length(sLocation));
sNode := TextBetween(sLocation, '', sDelimiter);
While Assigned(oNode) And (oNode.Text <> sNode) Do
oNode := oNode.GetNext;
If Assigned(oNode) Then
Result := SelectNode2(oNode, TextBetween(sLocation, sDelimiter, ''))
Else
Result := False;
End
Else
Result := False;
End;
- bah - several edits as I replace my own library routines with stuff you're likely to have :-( Sorry about that