Member Avatar for Member #892855

Hello Guys,
Am having a new assignment and a new problem. I should make C# application witch shows drive letters in combo box, directories and only .txt files in tree view, and I should be able to open text file from tree view in text box using Open button. I all ready have code to show me drives letters in combo box, but I don’t know how to get tree view from selected drive in tree view control.
Thanks all for helping me.

private void Form1_Load(object sender, EventArgs e)
        {
            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
            for (int i = 0; i <= drives.Length - 1; i++)
            {
                comboBox1.Items.Add(drives[i].Name);
                comboBox1.SelectedIndex = -1;
            }
        }

Dani AI

Generated

Good assignment for learning TreeView lazy-loading. Since you must keep drives in a ComboBox (agree with that one tree is simpler, but requirements are requirements), the most reliable pattern here is: store the real filesystem path in each node’s Tag, add a one-child placeholder to folders so they show an expand arrow, and populate children in BeforeExpand. That avoids fragile string concatenation with FullPath and keeps display names separate from actual paths.

Example BeforeExpand that lists folders and only .txt files, safely:

private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
    var dir = e.Node.Tag as string;
    if (string.IsNullOrEmpty(dir)) return;

    e.Node.Nodes.Clear(); // remove the placeholder
    try
    {
        foreach (var d in Directory.EnumerateDirectories(dir))
        {
            var n = new TreeNode(Path.GetFileName(d)) { Tag = d };
            n.Nodes.Add(new TreeNode()); // placeholder so it can expand later
            e.Node.Nodes.Add(n);
        }
        foreach (var f in Directory.EnumerateFiles(dir, "*.txt", SearchOption.TopDirectoryOnly))
            e.Node.Nodes.Add(new TreeNode(Path.GetFileName(f)) { Tag = f });
    }
    catch (UnauthorizedAccessException) { /* skip protected folders */ }
    catch (IOException) { /* skip missing/unavailable paths */ }
}

Hookup tips for if “nothing happens”:

  • Make sure events are wired (Designer or code): SelectedIndexChanged for the ComboBox and BeforeExpand for the TreeView.
  • When a drive is selected, create a single root node like new TreeNode(driveRoot) { Tag = driveRoot }, add one dummy child, and assign it to treeView1.Nodes.
  • For the Open button, read from the node’s Tag, not from FullPath:
    if (treeView1.SelectedNode?.Tag is string p && p.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)) richTextBox1.Text = File.ReadAllText(p);

Also watch for duplicates: clear nodes before repopulating, as shown above. If you want auto-populate, set the ComboBox’s SelectedIndex after filling it.

Recommended Answers

All 8 Replies

Why would you have drives in seperated combo? Wouldn`t be better to have all in treeView?

Member Avatar for Member #892855

Like I said.. This is assignment witch I have to solve. I must have it separated. It would be probably much easier to have all in one place.

Member Avatar for Member #892855

I found the Answer. Maybe it can help to someone else.

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;
using System.IO;

namespace Assignment___Tekst_čitač
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }


        private void Form1_Load(object sender, EventArgs e)
        {
           
            DriveInfo[] drives = DriveInfo.GetDrives();
            for (int i = 0; i <= drives.Length - 1; i++)
            {
                comboBox1.Items.Add(drives[i].Name);
                comboBox1.SelectedIndex = -1;
            }
        }
            

        

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            
            DirectoryInfo path = new DirectoryInfo(comboBox1.SelectedItem.ToString());
            
            
            try
            {
                foreach (DirectoryInfo dir in path.GetDirectories())
                {
                    TreeNode node = treeView1.Nodes.Add(dir.Name);
                    node.Nodes.Add(" ");
                }
                
                foreach (FileInfo file in path.GetFiles())
                {
                    if (file.Extension.ToLower() == ".txt")
                    {
                        TreeNode node = treeView1.Nodes.Add(file.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

       

        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            try
            {
               
                TreeNode courentNode = e.Node;
                DirectoryInfo folderPaht = new DirectoryInfo(comboBox1.SelectedItem + courentNode.FullPath);
                
                foreach (DirectoryInfo dir in folderPaht.GetDirectories())
                {
                    string fileName = dir.Name;
                    TreeNode node = courentNode.Nodes.Add(fileName);
                    node.Nodes.Add(" ");
                }
                
                foreach (FileInfo file in folderPaht.GetFiles())
                {
                    string ext = file.Extension;
                    if (ext.ToLower() == ".txt")
                    {
                        TreeNode newNode = courentNode.Nodes.Add(file.Name);
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            string fulPath = comboBox1.SelectedItem + treeView1.SelectedNode.FullPath;
            if (fulPath.ToLower().EndsWith(".txt"))
            {
                StreamReader read = new StreamReader(fulPath);
                richTextBox1.Text = read.ReadToEnd();
                read.Close();
            }
            else
                MessageBox.Show("");
        }
  
    }
}

Where do you have subdirectories?

Member Avatar for Member #892855

In this BeforeExpand event.

private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            try
            {
               
                TreeNode courentNode = e.Node;
                DirectoryInfo folderPaht = new DirectoryInfo(comboBox1.SelectedItem + courentNode.FullPath);
                
                foreach (DirectoryInfo dir in folderPaht.GetDirectories())
                {
                    string fileName = dir.Name;
                    TreeNode node = courentNode.Nodes.Add(fileName);
                    node.Nodes.Add(" ");
                }
          
            }
          }

This code for assignment TekstČitač doesn't work for me. I tried, but nothing happens. Is it working for someone else?

thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.