Use TreeView to display Directories : TreeView « GUI Windows Forms « C# / CSharp Tutorial

C# / CSharp Tutorial
1. Language Basics
2. Data Type
3. Operator
4. Statement
5. String
6. struct
7. Class
8. Operator Overload
9. delegate
10. Attribute
11. Data Structure
12. Assembly
13. Date Time
14. Development
15. File Directory Stream
16. Preprocessing Directives
17. Regular Expression
18. Generic
19. Reflection
20. Thread
21. I18N Internationalization
22. GUI Windows Forms
23. 2D
24. Design Patterns
25. Windows
26. XML
27. ADO.Net
28. Network
29. Directory Services
30. Security
31. unsafe
Java
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
C# / CSharp Tutorial » GUI Windows Forms » TreeView 
22. 31. 2. Use TreeView to display Directories
/* Quote from 

Programming .NET Windows Applications

By Jesse Liberty, Dan Hurwitz
First Edition October 2003 
Pages: 1246 (More details)
*/

using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;        // necessary for Directory info

public class TreeViewDirectories : Form
{
  TreeView tvw;
  CheckBox cb;
  Button btnSelected;
  Button btnExpand;
  Button btnExpandAll;
  Button btnCollapse;
  Button btnCollapseAll;
  Button btnToggle;

  public TreeViewDirectories()
  {
    Size = new Size(400,600);

    ImageList imgList = new ImageList();
    Image img;

    String[] arFiles = {"1.ico","2.ico","3.ico",".ico"};


    for (int i = 0; i < arFiles.Length; i++)
    {
      img = Image.FromFile(arFiles[i]);
      imgList.Images.Add(img);
    }

    tvw = new TreeView();
    tvw.Parent = this;
    tvw.Location = new Point(10,10);
    tvw.Size = new Size(ClientSize.Width - 20, Height - 200);
    tvw.Anchor = AnchorStyles.Top | AnchorStyles.Left | 
          AnchorStyles.Right | AnchorStyles.Bottom;
    tvw.BackColor = Color.Moccasin;
    tvw.ForeColor = Color.DarkRed;
    tvw.BorderStyle = BorderStyle.Fixed3D;
    tvw.FullRowSelect = false;    
    tvw.ShowLines = true;      
    tvw.ShowPlusMinus = true;    
    tvw.Scrollable = true;      
    tvw.HideSelection = false;  
    tvw.HotTracking = true;  
    tvw.ImageList = imgList;
    tvw.ImageIndex = 1;
    tvw.SelectedImageIndex = 2;
    tvw.Indent = 35;
    tvw.Font = new Font("Times New Roman"20f);
    tvw.ItemHeight = tvw.Font.Height * 2;
    tvw.BeforeExpand += new TreeViewCancelEventHandler(tvw_BeforeExpand);

    cb = new CheckBox();
    cb.Parent = this;
    cb.Location = new Point((Width - cb.Width10, tvw.Bottom + 25);
    cb.Text = "Show Files";
    cb.Anchor = AnchorStyles.Bottom;
    cb.CheckedChanged += new EventHandler(cb_CheckedChanged);

    btnSelected = new Button();
    btnSelected.Parent = this;
    btnSelected.Text = "&SelectedNode";
    int xSize = ((int)(Font.Height * .75* btnSelected.Text.Length);
    int ySize = Font.Height + 10;
    btnSelected.Size = new Size(xSize, ySize);
    btnSelected.Location = new Point(cb.Left, cb.Bottom + ySize);
    btnSelected.Anchor = AnchorStyles.Bottom;
    btnSelected.Click += new EventHandler(btnSelected_Click);

    btnToggle = new Button();
    btnToggle.Parent = this;
    btnToggle.Location = new Point((Width - cb.Width10,
                                      cb.Top);
    btnToggle.Text = "&Toggle";
    btnToggle.Size = new Size(btnSelected.Width, btnSelected.Height);
    btnToggle.Anchor = AnchorStyles.Bottom;
    btnToggle.Click += new EventHandler(btnToggle_Click);

    btnExpand = new Button();
    btnExpand.Parent = this;
    btnExpand.Location = new Point(btnToggle.Left, btnToggle.Bottom);
    btnExpand.Text = "&Expand";
    btnExpand.Size = new Size(btnSelected.Width, btnSelected.Height);
    btnExpand.Anchor = AnchorStyles.Bottom;
    btnExpand.Click += new EventHandler(btnExpand_Click);

    btnExpandAll = new Button();
    btnExpandAll.Parent = this;
    btnExpandAll.Location = new Point(btnExpand.Left, btnExpand.Bottom);
    btnExpandAll.Text = "Expand &All";
    btnExpandAll.Size = new Size(btnSelected.Width, btnSelected.Height);
    btnExpandAll.Anchor = AnchorStyles.Bottom;
    btnExpandAll.Click += new EventHandler(btnExpandAll_Click);

    btnCollapse = new Button();
    btnCollapse.Parent = this;
    btnCollapse.Location = new Point(btnExpandAll.Left, btnExpandAll.Bottom);
    btnCollapse.Text = "&Collapse";
    btnCollapse.Size = new Size(btnSelected.Width, btnSelected.Height);
    btnCollapse.Anchor = AnchorStyles.Bottom;
    btnCollapse.Click += new EventHandler(btnCollapse_Click);

    btnCollapseAll = new Button();
    btnCollapseAll.Parent = this;
    btnCollapseAll.Location = new Point(btnCollapse.Left, btnCollapse.Bottom);
    btnCollapseAll.Text = "Colla&pse All";
    btnCollapseAll.Size = new Size(btnSelected.Width, btnSelected.Height);
    btnCollapseAll.Anchor = AnchorStyles.Bottom;
    btnCollapseAll.Click += new EventHandler(btnCollapseAll_Click);

    FillDirectoryTree();
  }

  static void Main() 
  {
    Application.Run(new TreeViewDirectories());
  }

  private void FillDirectoryTree()
  {
    tvw.BeginUpdate();
    tvw.Nodes.Clear();

    string[] strDrives = Environment.GetLogicalDrives();
        foreach (string rootDirectoryName in strDrives)
       {
      try 
      {
        Directory.GetDirectories(rootDirectoryName);

        TreeNode ndRoot = new TreeNode(rootDirectoryName);

        tvw.Nodes.Add(ndRoot);
        if (ndRoot.Index % == 0)
        {
          ndRoot.BackColor = Color.LightYellow;
          ndRoot.ForeColor = Color.Green;
        }

        GetSubDirectoryNodes(ndRoot, cb.Checked);
      }
      catch  (System.IO.IOException)
      {
            }
      catch  (Exception e)
      {
        MessageBox.Show(e.Message);
            }
    }
     
      tvw.EndUpdate();
     
  }

  private void GetSubDirectoryNodes(TreeNode parentNode, bool getFileNames)
  {
    DirectoryInfo di = new DirectoryInfo(parentNode.FullPath);
    if ((di.Attributes & FileAttributes.Directory== 0)
    {
      return;
    }

    parentNode.Nodes.Clear();

    string[] arSubs = Directory.GetDirectories(parentNode.FullPath);

    foreach (string subDir in arSubs)
    {
          DirectoryInfo dirInfo = new DirectoryInfo(subDir);
            if ((dirInfo.Attributes & FileAttributes.Hidden)!= 0)
            {
               continue;
            }

      TreeNode subNode = new TreeNode(dirInfo.Name);
      parentNode.Nodes.Add(subNode);
        
      //  Set colors based on Index property.
      if (subNode.Index % == 0)
        subNode.BackColor = Color.LightPink;
    }

    if (getFileNames)
    {
            //  Get any files for this node.
          string[] files = Directory.GetFiles(parentNode.FullPath);

            // After placing the nodes, 
            // now place the files in that subdirectory.
            foreach (string str in files)
            {
        FileInfo fi = new FileInfo(str);
        TreeNode fileNode = new TreeNode(fi.Name);
        parentNode.Nodes.Add(fileNode);

        //  Set the icon
        fileNode.ImageIndex = 0;
        fileNode.SelectedImageIndex = 3;

        //  Set colors based on Index property.
        if (fileNode.Index % == 0)
          fileNode.BackColor = Color.LightGreen;
            }
    }
  }  // close GetSubDirectoryNodes



  private void cb_CheckedChanged(object sender, EventArgs e)
  {
    FillDirectoryTree();
  }

  private void tvw_BeforeExpand(object sender, 
                TreeViewCancelEventArgs e)
  {
    tvw.BeginUpdate();

    foreach (TreeNode tn in e.Node.Nodes)
    {
      GetSubDirectoryNodes(tn, cb.Checked);
    }

    tvw.EndUpdate();      
  }    

  private void btnSelected_Click(object sender, EventArgs e)
  {
    MessageBox.Show(tvw.SelectedNode.ToString() "\n" +
        "FullPath:\t" + tvw.SelectedNode.FullPath.ToString() "\n" +
           "Index:\t" + tvw.SelectedNode.Index.ToString());
  }

  private void btnExpand_Click(object sender, EventArgs e)
  {
    tvw.SelectedNode.Expand();
  }

  private void btnExpandAll_Click(object sender, EventArgs e)
  {
    tvw.SelectedNode.ExpandAll();
  }

  private void btnCollapse_Click(object sender, EventArgs e)
  {
    tvw.SelectedNode.Collapse();
  }

  private void btnCollapseAll_Click(object sender, EventArgs e)
  {
    tvw.CollapseAll();
  }

  private void btnToggle_Click(object sender, EventArgs e)
  {
    tvw.SelectedNode.Toggle();
  }
}
22. 31. TreeView
22. 31. 1. TreeView selection event
22. 31. 2. Use TreeView to display Directories
22. 31. 3. TreeView: Add NodesTreeView: Add Nodes
22. 31. 4. Tree node foreground and background color, tooltipsTree node foreground and background color, tooltips
w___w___w___.__ja__v__a__2___s__._c___o_m__ | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.