Link to home
Start Free TrialLog in
Avatar of Unimatrix_001
Unimatrix_001Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Adding a Node to a TreeNode with full name.

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
Avatar of nipunu
nipunu

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
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Unimatrix_001

ASKER

Thank you - not quite sure why my search didn't find that. :S
Oh man - the difference between the nice elegant code in the link you posted and my attempts are massive. :(
Glad it was helpful...just keep coding and it will come together eventually.  =)