We help IT Professionals succeed at work.

Adding a Node to a TreeNode with full name.

Unimatrix_001
Unimatrix_001 asked
on
Hi,

I've got a few Strings as:

Dir1\Dir2\File1
Dir1\Dir2\File2
Dir1\File1
Dir2\File1

etc.

What I'm wanting to do is create TreeNodes from these Strings, so that I end up with something like:

Root
	Dir1
		Dir2
			File1
			File2
		File1
	Dir2
		File1

Open in new window


Without having to manually parse each string, is there a method to do this?

Thanks,
Uni
Comment
Watch Question

Commented:
First drag drop one TreeView control on the form

using System.IO;
private void Form1_Load(object sender, EventArgs e)
{
    TreeNode rootnode = new TreeNode(@"C:\");
    treeView1.Nodes.Add(rootnode);
    FillChildNodes(rootnode);
    treeView1.Nodes[0].Expand();
}
void FillChildNodes(TreeNode node)
{
   try
   {
       DirectoryInfo dirs = new DirectoryInfo(node.FullPath);
       foreach (DirectoryInfo dir in dirs.GetDirectories())
       {
           TreeNode newnode = new TreeNode(dir.Name);
           node.Nodes.Add(newnode);
           newnode.Nodes.Add("*");
       }
   }
   catch(Exception ex)
   {
        MessageBox.Show(ex.Message.ToString());
   }
}
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
   if (e.Node.Nodes[0].Text == "*")
   {
       e.Node.Nodes.Clear();
       FillChildNodes(e.Node);
   }
}

Above code is for windows forms following is for web forms

Another Link - http://www.dotnetspider.com/resources/29711-Displaying-Directories-structure-using-Tree-View.aspx
High School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009
Commented:

Author

Commented:
Thank you - not quite sure why my search didn't find that. :S

Author

Commented:
Oh man - the difference between the nice elegant code in the link you posted and my attempts are massive. :(
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009

Commented:
Glad it was helpful...just keep coding and it will come together eventually.  =)