Convert TStringList pattern to a TTreeView

saravananvg
saravananvg used Ask the Experts™
on
Hi Experts,

    I have a TStringList which contains Strings in the following pattern

Folderx
Folderx\Folder1
Folderx\Folder1\Folder11
Foldery
Foldery\Folder1
Foldery\Folder1\Folder11
.......
Similar to the Directory and File Paths.
I would like to represent the same in a TreeView as follows.
Folderx
  |_Folder1
            |_Folder11
Foldery
 |_Folder1
            |_Folder11
......
   It can go upto any level.
   It is very urgent and any help is appreciated.

with regards,
Saravanan
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Geert GOracle dba
Top Expert 2009

Commented:
Emmanuel PASQUIERFreelance Project Manager
Top Expert 2010

Commented:
for this sample code, you must use StrUtils, and have a TreeView:TTreeView component in your form

Call like that :
  CreateNodesFromString('Folder 1\Folder 1.1\Folder 1.1.2');
Or
  CreateNodesFromList(MyStringList);
function TformTree.FindNodeOrCreate(node:TTreeNode;nt:String):TTreeNode;
Var
 i:integer;
begin
 if node=nil
  Then Result:=TreeView.Items.GetFirstNode
  Else Result:=node.GetFirstChild;
 While Assigned(Result) And (Result.Text<>nt) do Result:=Result.getNextSibling;
 if Assigned(Result) Then Exit;
 Result:=TreeView.Items.AddChild(node,nt);
end;
 
procedure TformTree.CreateNodesFromString(S:String);
Var
 N:TTreeNode;
 P:Integer;
begin
 N:=nil;
 While S<>'' do
  begin
   P:=Pos('\',S);
   if P=0 Then P:=Length(S)+1;
   N:=FindNodeOrCreate(N,LeftStr(S,P-1));
   S:=Copy(S,P+1,Length(S));
  end;
end;
 
procedure TformTree.CreateNodesFromList(L:TStrings);
Var
 i:integer;
begin
 for i:=0 to L.Count-1 do CreateNodesFromString(L[i]);
end;

Open in new window

Author

Commented:
Hi Epasquier

   Thanks for your code, it seems to be working. But I need to know how to get the value of the selected node as follows.

   When I select say Folder11, it has to give me the entire path
   Foldery\Folder1\Folder11.

with regards,
Saravanan
Freelance Project Manager
Top Expert 2010
Commented:
Is that not worth a few extra points ? ;o)
procedure TformTree.TreeViewChange(Sender: TObject; Node: TTreeNode);
Var
 FullPath:String;
begin
 FullPath:='';
 While Assigned(Node) do 
  begin
   FullPath:=Node.Text+'\'+FullPath;
   Node:=Node.Parent;
  end;
end;

Open in new window

Author

Commented:
Thanks for the solution

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial