Ninjas Edits
Ninjas Edits

Reputation: 27

Windows forms tree view show folder info

I have something like Explorer, where you chose some folder, and in tree view it displays it. And I need in the list box, to show the folder info, but the thing is, the folder info should only show when a specific folder is selected, but now I have only when I select the first folder, it shows all files that are in that folder. Here is the code for now

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    DirectoryInfo directoryInfo;
    private void directoryToolStripMenuItem_Click(object sender, EventArgs e)
    {
        folderbrowser_dialog.ShowDialog();
        if (folderbrowser_dialog.SelectedPath != null)
        {
            directoryInfo = new DirectoryInfo(folderbrowser_dialog.SelectedPath);
            if (directoryInfo.Exists)
            {
                BuildTree(directoryInfo, treeview.Nodes);
            }
        }
    }

    private void resetToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Restart();
    }

    private void BuildTree(DirectoryInfo directoryInfo, TreeNodeCollection addInMe)
    {
        TreeNode root = addInMe.Add(directoryInfo.Name);
        foreach (DirectoryInfo subdir in directoryInfo.GetDirectories())
        {
            BuildTree(subdir, root.Nodes);
        }           

        FileInfo[] Files = directoryInfo.GetFiles("*");
        foreach (FileInfo file in Files)
        {
            listbox.Items.Add(file.Name);
        }
    }
}

Upvotes: 1

Views: 967

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129687

Your question is a little unclear, but it sounds like you are asking how you can show the correct files in the ListBox whenever you select a folder in the tree. Here is how you do that:

In your BuildTree method, after you create the TreeNode, set the Name property on the node to the FullName of the folder that node represents.

private void BuildTree(DirectoryInfo directoryInfo, TreeNodeCollection addInMe)
{
    TreeNode root = addInMe.Add(directoryInfo.Name);
    root.Name = directoryInfo.FullName;
    ...
}

Then, add an AfterSelect event handler on the TreeView. In the event handler, create a DirectoryInfo using the Name of the selected node (e.Node.Name). Clear the ListBox and then use the same loop you have now in BuildTree to repopulate it.

private void treeview_AfterSelect(object sender, TreeViewEventArgs e)
{
    DirectoryInfo directoryInfo = new DirectoryInfo(e.Node.Name);
    FileInfo[] Files = directoryInfo.GetFiles("*");
    listbox.Items.Clear();
    foreach (FileInfo file in Files)
    {
        listbox.Items.Add(file.Name);
    }
}

Upvotes: 1

Related Questions