CrownFord
CrownFord

Reputation: 719

How to use treeView to list the Files within sub Directories without showing the root directory?

This code works fine:

    private void Form1_Load(object sender, EventArgs e)
    {
       PopulateTree(@"C:\treeview", treeView1.Nodes.Add("I want to remove this node"));
    }
    public void PopulateTree(string dir, TreeNode node)
    {
        DirectoryInfo directory = new DirectoryInfo(dir);
        foreach (DirectoryInfo d in directory.GetDirectories())
        {
            TreeNode t = new TreeNode(d.Name);
            PopulateTree(d.FullName, t);
            node.Nodes.Add(t);
        }
        foreach (FileInfo f in directory.GetFiles())
        {
            TreeNode t = new TreeNode(f.Name);
            node.Nodes.Add(t);
        }
    }

BUT, I do not want to show the main(=root) directory(=folder) on the top of the list of sub-directories, I just want to show the sub-directoriesas shown down in the illustration. enter image description here

Upvotes: 0

Views: 2544

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273844

  PopulateTree(@"C:\treeview", treeView1.Nodes);

public void PopulateTree(string dir, TreeNodeCollection nodes)
{
    DirectoryInfo directory = new DirectoryInfo(dir);
    foreach (DirectoryInfo d in directory.GetDirectories())
    {
        TreeNode t = new TreeNode(d.Name);
        nodes.Add(t);
        PopulateTree(d.FullName, t.Nodes);            
    }
    foreach (FileInfo f in directory.GetFiles())
    {
        TreeNode t = new TreeNode(f.Name);
        nodes.Add(t);
    }
}

Upvotes: 1

kmatyaszek
kmatyaszek

Reputation: 19296

Try this:

public void PopulateTree(string dir, TreeNode node)
{
    DirectoryInfo directory = new DirectoryInfo(dir);
    foreach (DirectoryInfo d in directory.GetDirectories())
    {
        TreeNode t = new TreeNode(d.Name);
        if (node != null) node.Nodes.Add(t);
        else treeView1.Nodes.Add(t);
        PopulateTree(d.FullName, t);      
    }
    foreach (FileInfo f in directory.GetFiles())
    {
        TreeNode t = new TreeNode(f.Name);
        if (node != null) node.Nodes.Add(t);
        else treeView1.Nodes.Add(t);
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    PopulateTree(@"C:\treeview", null);
}

Upvotes: 1

Related Questions