• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 236
  • Last Modified:

Need Treeview Help

Below is a very simple Treeview code that I would need some help with.

Problem 1:
How do I get all the subfolders? as you can see now it only shows 2 levels (Any simple and easy to understand recursive rewrite of the code ?).

Problem 2:
How do I start to populate the treeview if I have several starting Locations (root Folders)?
namespace treeview_simple
{
    public partial class Form1 : Form
    {
 
        public Form1()
        {
            InitializeComponent();
 
            //Starting/Root folder 1 
            string Location = @"\\Home\Bookfolder1\";
            DirectoryInfo dir = new DirectoryInfo(Location);
 
            //Create Title Node
            TreeNode booktitles = treeView1.Nodes.Add("Books");
 
            foreach (System.IO.DirectoryInfo g in dir.GetDirectories())
            {
                //LOAD Location1 FOLDERS 
                 TreeNode MainNext = booktitles.Nodes.Add(g.Name);
 
                 DirectoryInfo subdir = new DirectoryInfo(g.FullName);
                   foreach (System.IO.DirectoryInfo x in subdir.GetDirectories())
                        {
                       //LOAD 1st Level Subfolders
                            TreeNode MainNext2 = MainNext.Nodes.Add(x.Name);
                        }
                    }
 
 
            }
    
    }
 
    }

Open in new window

0
Smyken
Asked:
Smyken
  • 4
  • 3
1 Solution
 
CuteBugCommented:
This code should solve your problem
public Form1()
{
            InitializeComponent();
            string Location = @"\\Home\Bookfolder1\";
            DirectoryInfo dir = new DirectoryInfo(Location);
 
            //Create Title Node
            TreeNode booktitles = treeView1.Nodes.Add("Books");
            AddNode(dir, booktitles);
}
 
 
 
public void AddNode(System.IO.DirectoryInfo dir, TreeNode node)
{
    foreach (System.IO.DirectoryInfo dInfo in dir.GetDirectories())
    {
         TreeNode mainNext = node.Nodes.Add(dInfo.Name);
         AddNode(dInfo, mainNext);
    }
}

Open in new window

0
 
HarryNSCommented:

string substringDirectory;
private void Form7_Load(object sender, EventArgs e)
        {
            this.treeView1.Nodes.Clear();
 
            String path = "c:\\hari\\";
 
            treeView1.Nodes.Add(path);
            PopulateTreeView(path, treeView1.Nodes[0]);
      
        }
public void PopulateTreeView(string directoryValue, TreeNode parentNode)
        {
            string[] directoryArray =
             System.IO.Directory.GetDirectories(directoryValue);
 
            try
            {
                if (directoryArray.Length != 0)
                {
                    foreach (string directory in directoryArray)
                    {
                        substringDirectory = directory.Substring(
                        directory.LastIndexOf('\\') + 1,
                        directory.Length - directory.LastIndexOf('\\') - 1);
 
                        TreeNode myNode = new TreeNode(substringDirectory);
 
                        parentNode.Nodes.Add(myNode);
 
                        PopulateTreeView(directory, myNode);
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                parentNode.Nodes.Add("Access denied");
            } // end catch
 
        }

Open in new window

0
 
CuteBugCommented:
For your Problem No. 2:
A tree has only one root folder.

So you can have one Root Folder for your tree (say "ParentNode") and under this node you can add the various starting locations as child nodes.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
SmykenAuthor Commented:
So regarding my problem nr2:

Is it not possible at all to add several other (string Location = @"\\Home\Bookfolder1\";) to my root node (TreeNode booktitles)  ?
0
 
SmykenAuthor Commented:
I tryied your code HarryNS

Started new project and added new treeView1 and pasted your code but the treeview is empty, I also changed path and Form7_Load to Form1_Load.


What am I doing wrong ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsFormsApplication18
{
 
    public partial class Form1 : Form
    {
        string substringDirectory;
        private void Form1_Load(object sender, EventArgs e)
        {
            this.treeView1.Nodes.Clear();
 
            String path = @"c:\temp\";
 
            treeView1.Nodes.Add(path);
            PopulateTreeView(path, treeView1.Nodes[0]);
 
        }
        public void PopulateTreeView(string directoryValue, TreeNode parentNode)
        {
            string[] directoryArray = System.IO.Directory.GetDirectories(directoryValue);
 
            try
            {
                if (directoryArray.Length != 0)
                {
                    foreach (string directory in directoryArray)
                    {
                        substringDirectory = directory.Substring(directory.LastIndexOf('\\') + 1, directory.Length - directory.LastIndexOf('\\') - 1);
 
                        TreeNode myNode = new TreeNode(substringDirectory);
 
                        parentNode.Nodes.Add(myNode);
 
                        PopulateTreeView(directory, myNode);
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                parentNode.Nodes.Add("Access denied");
            } // end catch
 
        }
 
        public Form1()
        {
 
            InitializeComponent();
 
        }
 
 
 
    }
}

Open in new window

0
 
CuteBugCommented:
Hi Symken,
    Yes you can for the problem nr 2

Look at the code below:

public Form1()
{
            InitializeComponent();
            string Location = @"\\Home\Bookfolder1\";
            DirectoryInfo dir = new DirectoryInfo(Location);
 
            //Create Title Node
            TreeNode booktitles = treeView1.Nodes.Add("Books");
            AddNode(dir, booktitles);
 
            Location = @"\\Home\Bookfolder2\";
            dir = new DirectoryInfo(Location);
            AddNode(dir, booktitles);            
}
 
 
 
public void AddNode(System.IO.DirectoryInfo dir, TreeNode node)
{
    foreach (System.IO.DirectoryInfo dInfo in dir.GetDirectories())
    {
         TreeNode mainNext = node.Nodes.Add(dInfo.Name);
         AddNode(dInfo, mainNext);
    }
}

Open in new window

0
 
SmykenAuthor Commented:
Thank You a lot CuteBug !

Worked like a charm !

May I ask if you could add the exceptionhandler incase a Path is not existing or is not allowed to access ?

I will reward you the points after I see a response from you, if you don't have time or will to add the exceptionhandler just say so and I will reward you the points for your easy and clean code above 8=)

I will also post a follow up after I close this one about how to add the paths by User at run time and make them presistent after application exit.

Anyhow tks a lot !
0
 
CuteBugCommented:
You are welcome Smyken!

Here is the code with exception handling added
public Form1()
{
            InitializeComponent();
            string Location = @"\\Home\Bookfolder1\";
            DirectoryInfo dir = new DirectoryInfo(Location);
 
            //Create Title Node
            TreeNode booktitles = treeView1.Nodes.Add("Books");
            AddNode(dir, booktitles);
 
            Location = @"\\Home\Bookfolder2\";
            dir = new DirectoryInfo(Location);
            AddNode(dir, booktitles);            
}
 
 
 
public void AddNode(System.IO.DirectoryInfo dir, TreeNode node)
{
    try
    {
        foreach (System.IO.DirectoryInfo dInfo in dir.GetDirectories())
        {
             TreeNode mainNext = node.Nodes.Add(dInfo.Name);
             AddNode(dInfo, mainNext);
        }
    }
    catch(UnauthorizedAccessException)
    {
        node.Nodes.Add("Access denied");
    }
    // Catch other exceptions
    catch(Exception)
    {
        node.Nodes.Add("Error accessing directory!");
    }
}

Open in new window

0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now