Csharp/C Sharp/GUI Windows Form/TreeView — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 15:31, 26 мая 2010

Add Nodes to TreeView

 
using System;
using System.Drawing;
using System.Windows.Forms;
   
class SimpleTreeView: Form
{
     public static void Main()
     {
          Application.Run(new SimpleTreeView());
     }
     public SimpleTreeView()
     {
          Text = "Simple Tree View";
   
          TreeView tree = new TreeView();
          tree.Parent = this;
          tree.Dock = DockStyle.Fill;
   
          tree.Nodes.Add("Animal");
          tree.Nodes[0].Nodes.Add("A");
          tree.Nodes[0].Nodes[0].Nodes.Add("A1");
          tree.Nodes[0].Nodes[0].Nodes.Add("A2");
          tree.Nodes[0].Nodes[0].Nodes.Add("A3");
          tree.Nodes[0].Nodes.Add("B");
          tree.Nodes[0].Nodes[1].Nodes.Add("B1");
          tree.Nodes[0].Nodes[1].Nodes.Add("B2");
          tree.Nodes[0].Nodes.Add("C");
          tree.Nodes[0].Nodes[2].Nodes.Add("C1");
          tree.Nodes[0].Nodes[2].Nodes.Add("C2");
          tree.Nodes[0].Nodes[2].Nodes.Add("C3");
          tree.Nodes.Add("D");
          tree.Nodes[1].Nodes.Add("D1");
          tree.Nodes[1].Nodes.Add("D2");
          tree.Nodes[1].Nodes.Add("D3");
          tree.Nodes.Add("E");
          tree.Nodes[2].Nodes.Add("E1");
          tree.Nodes[2].Nodes.Add("E2");
          tree.Nodes[2].Nodes.Add("E3");
     }
}


Custom TreeView

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald
Publisher: Apress
ISBN: 1590590457
*/
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace CustomTreeView
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class CustomTreeView : System.Windows.Forms.Form
    {
        internal System.Windows.Forms.ImageList imagesTree;
        private ProjectTree tree;
        private System.ruponentModel.IContainer components;
        public CustomTreeView()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ruponents = new System.ruponentModel.Container();
//            System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(CustomTreeView));
            this.imagesTree = new System.Windows.Forms.ImageList(this.ruponents);
            this.tree = new ProjectTree();
            this.SuspendLayout();
            // 
            // imagesTree
            // 
            this.imagesTree.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
            this.imagesTree.ImageSize = new System.Drawing.Size(16, 16);
//            this.imagesTree.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imagesTree.ImageStream")));
            this.imagesTree.TransparentColor = System.Drawing.Color.Transparent;
            // 
            // tree
            // 
            this.tree.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.tree.ImageList = this.imagesTree;
            this.tree.Location = new System.Drawing.Point(8, 4);
            this.tree.Name = "tree";
            this.tree.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
                                                                             new System.Windows.Forms.TreeNode("Unassigned", 0, 0),
                                                                             new System.Windows.Forms.TreeNode("In Progress", 1, 1),
                                                                             new System.Windows.Forms.TreeNode("Closed", 2, 2)});
            this.tree.Scrollable = false;
            this.tree.Size = new System.Drawing.Size(320, 296);
            this.tree.TabIndex = 0;
            // 
            // CustomTreeView
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(336, 310);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.tree});
            this.Name = "CustomTreeView";
            this.Text = "ProjectUserTree";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
        }
        #endregion
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new CustomTreeView());
        }
        private void Form1_Load(object sender, System.EventArgs e)
        {
            tree.AddProject("Migration to .NET", ProjectTree.StatusType.InProgress);
            tree.AddProject("Revamp pricing site", ProjectTree.StatusType.Unassigned);
            tree.AddProject("Prepare L-DAP feasibility report", ProjectTree.StatusType.Unassigned);
            tree.AddProject("Update E201-G to Windows XP", ProjectTree.StatusType.Closed);
            tree.AddProject("Annual meeting", ProjectTree.StatusType.Closed);
        }
    }


        public class ProjectTree : TreeView
        {
            // Use an enumeration to represent the three types of nodes.
            // Specific numbers correspond to the database field code.
            public enum StatusType
            {
                Unassigned = 101,
                InProgress = 102,
                Closed = 103
            }
            // Store references to the three main node branches.
            private TreeNode nodeUnassigned = new TreeNode("Unassigned", 0, 0);
            private TreeNode nodeInProgress = new TreeNode("In Progress", 1, 1);
            private TreeNode nodeClosed = new TreeNode("Closed", 2, 2);
            // Add the main level of nodes when the control is instantiated.
            public ProjectTree() : base()
            {
                base.Nodes.Add(nodeUnassigned);
                base.Nodes.Add(nodeInProgress);
                base.Nodes.Add(nodeClosed);
            }
            // Provide a specialized method the client can use to add nodes.
            public void AddProject(string name, StatusType status)
            {
                TreeNode nodeNew = new TreeNode(name, 3, 4);
                nodeNew.Tag = status;
                switch (status)
                {
                    case StatusType.Unassigned:
                        nodeUnassigned.Nodes.Add(nodeNew);
                        break;
                    case StatusType.InProgress:
                        nodeInProgress.Nodes.Add(nodeNew);
                        break;
                    case StatusType.Closed:
                        nodeClosed.Nodes.Add(nodeNew);
                        break;
                }
            }
        }
    public class ProjectUserTree : TreeView
    {
        // Use an enumeration to represent the three types of nodes.
        public enum NodeType
        {
            Project,
            User
        }
        // Define a new type of higher-level event for node selection.
        public delegate void ItemSelectEventHandler(object sender,
            ItemSelectEventArgs e);
            public class ItemSelectEventArgs : EventArgs
            {
                public NodeType Type;
                public DataRow ItemData;
            }
        // Define the events that use this signature and event arguments.
        public event ItemSelectEventHandler UserSelect;
        public event ItemSelectEventHandler ProjectSelect;
        
        // Store references to the two main node branches.
        private TreeNode nodeProjects = new TreeNode("Projects", 0, 0);
        private TreeNode nodeUsers = new TreeNode("Users", 1, 1);
        // Add the main level of nodes when the control is instantiated.
        public ProjectUserTree() : base()
        {
            base.Nodes.Add(nodeProjects);
            base.Nodes.Add(nodeUsers);
        }
        // Provide a specialized method the client can use to add projects.
        // Store the corresponding DataRow.
        public void AddProject(DataRow project)
        {
            TreeNode nodeNew = new TreeNode(project["Name"].ToString(), 2, 3);
            nodeNew.Tag = project;
            nodeProjects.Nodes.Add(nodeNew);
        }
        // Provide a specialized method the client can use to add users.
        // Store the correspnding DataRow.
        public void AddUser(DataRow user)
        {
            TreeNode nodeNew = new TreeNode(user["Name"].ToString(), 2, 3);
            nodeNew.Tag = user;
            nodeUsers.Nodes.Add(nodeNew);
        }
        // When a node is selected, retrieve the DataRow and raise the event.
        protected override void OnAfterSelect(TreeViewEventArgs e)
         {
            base.OnAfterSelect(e);
                 ItemSelectEventArgs arg = new ItemSelectEventArgs();
                 arg.ItemData = (DataRow)e.Node.Tag;
                 if (e.Node.Parent == nodeProjects)
                 {
                     arg.Type = NodeType.Project;
                     ProjectSelect(this, arg);
                 }
                 else if (e.Node.Parent == nodeUsers)
                 {
                     arg.Type = NodeType.User;
                     UserSelect(this, arg);
                 }
             }
    }
}


Directory Tree Host

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald
Publisher: Apress
ISBN: 1590590457
*/
using System.IO;
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
namespace DirectoryTreeHost
{
    /// <summary>
    /// Summary description for DirectoryTreeHost.
    /// </summary>
    public class DirectoryTreeHost : System.Windows.Forms.Form
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ruponentModel.Container components = null;
        public DirectoryTreeHost()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if(components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            // 
            // DirectoryTreeHost
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Name = "DirectoryTreeHost";
            this.Text = "DirectoryTreeHost";
            this.Load += new System.EventHandler(this.DirectoryTreeHost_Load);
        }
        #endregion
        private void DirectoryTreeHost_Load(object sender, System.EventArgs e)
        {
            DirectoryTree dirTree = new 
                DirectoryTree();
            dirTree.Size = new Size(this.Width - 30, this.Height - 60);
            dirTree.Location = new Point(5, 5);
            dirTree.Drive = Char.Parse("C");
            this.Controls.Add(dirTree);
        }
        public static void Main()
        {
            Application.Run(new DirectoryTreeHost());
        }
    }
    public class DirectoryTree : TreeView
    {
        public delegate void DirectorySelectedDelegate(object sender,
            DirectorySelectedEventArgs e);
        public event DirectorySelectedDelegate DirectorySelected;
        
        private Char drive;
        public Char Drive
        {
            get
            {
                return drive;
            }
            set
            {
                drive = value;
                RefreshDisplay();
            }
        }
        
        // This is public so a Refresh can be triggered manually.
        public void RefreshDisplay()
        {
            // Erase the existing tree.
            this.Nodes.Clear();
            
            // Set the first node.
            TreeNode rootNode = new TreeNode(drive + ":\\");
            this.Nodes.Add(rootNode);
            
            // Fill the first level and expand it.
            Fill(rootNode);
            this.Nodes[0].Expand();
        }
        
        private void Fill(TreeNode dirNode)
        {
            DirectoryInfo dir = new DirectoryInfo(dirNode.FullPath);
            
            // An exception could be thrown in this code if you don"t
            // have sufficient security permissions for a file or directory.
            // You can catch and then ignore this exception.
            
            foreach (DirectoryInfo dirItem in dir.GetDirectories())
            {
                // Add node for the directory.
                TreeNode newNode = new TreeNode(dirItem.Name);
                dirNode.Nodes.Add(newNode);
                newNode.Nodes.Add("*");
            }
        }
        
        protected override void OnBeforeExpand(TreeViewCancelEventArgs e)
        {
            base.OnBeforeExpand(e);
            // If a dummy node is found, remove it and read the real directory list.
            if (e.Node.Nodes[0].Text == "*")
            {
                e.Node.Nodes.Clear();
                Fill(e.Node);
            }
        }
        
        protected override void OnAfterSelect(TreeViewEventArgs e)
        {
            base.OnAfterSelect(e);
            
            // Raise the DirectorySelected event.
            if (DirectorySelected != null)
            {
                DirectorySelected(this,
                    new DirectorySelectedEventArgs(e.Node.FullPath));
            }
        }
    }
    public class DirectorySelectedEventArgs : EventArgs
    {
        public string DirectoryName;
        public DirectorySelectedEventArgs(string directoryName)
        {
            this.DirectoryName = directoryName;
        }
    }

}


Drag and drop Tree Node

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
public class Form1 : Form
{
  private System.Windows.Forms.SplitContainer splitContainer1;
  private System.Windows.Forms.TreeView treeOne;
  private System.Windows.Forms.TreeView treeTwo;
  public Form1() {
        InitializeComponent();
    TreeNode node = treeOne.Nodes.Add("A");
    node.Nodes.Add("A1");
    node.Nodes.Add("A2");
    node.Expand();
    node = treeTwo.Nodes.Add("B");
    node.Nodes.Add("B1");
    node.Nodes.Add("B2");
    node.Expand();
    treeTwo.AllowDrop = true;
    treeOne.AllowDrop = true;
  }
  private void tree_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
  {
    TreeView tree = (TreeView)sender;
    TreeNode node = tree.GetNodeAt(e.X, e.Y);
    tree.SelectedNode = node;
    if (node != null)
    {
      tree.DoDragDrop(node, DragDropEffects.Copy);
    }
  }
  private void tree_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
  {
    TreeView tree = (TreeView)sender;
    e.Effect = DragDropEffects.None;
    TreeNode nodeSource = (TreeNode)e.Data.GetData(typeof(TreeNode));
    if (nodeSource != null)
    {
      if (nodeSource.TreeView != tree)
      {
        Point pt = new Point(e.X, e.Y);
        pt = tree.PointToClient(pt);
        TreeNode nodeTarget = tree.GetNodeAt(pt);
        if (nodeTarget != null)
        {
          e.Effect = DragDropEffects.Copy;
          tree.SelectedNode = nodeTarget;
        }
      }
    }
  }
  private void tree_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
  {
    TreeView tree = (TreeView)sender;
    Point pt = new Point(e.X, e.Y);
    pt = tree.PointToClient(pt);
    TreeNode nodeTarget = tree.GetNodeAt(pt);
    TreeNode nodeSource = (TreeNode)e.Data.GetData(typeof(TreeNode));
    nodeTarget.Nodes.Add((TreeNode)nodeSource.Clone());
    nodeTarget.Expand();
  }
  private void InitializeComponent()
  {
        this.splitContainer1 = new System.Windows.Forms.SplitContainer();
        this.treeOne = new System.Windows.Forms.TreeView();
        this.treeTwo = new System.Windows.Forms.TreeView();
        this.splitContainer1.Panel1.SuspendLayout();
        this.splitContainer1.Panel2.SuspendLayout();
        this.splitContainer1.SuspendLayout();
        this.SuspendLayout();
        // 
        // splitContainer1
        // 
        this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.splitContainer1.Location = new System.Drawing.Point(0, 0);
        this.splitContainer1.Name = "splitContainer1";
        // 
        // splitContainer1.Panel1
        // 
        this.splitContainer1.Panel1.Controls.Add(this.treeOne);
        // 
        // splitContainer1.Panel2
        // 
        this.splitContainer1.Panel2.Controls.Add(this.treeTwo);
        this.splitContainer1.Size = new System.Drawing.Size(456, 391);
        this.splitContainer1.SplitterDistance = 238;
        this.splitContainer1.TabIndex = 0;
        this.splitContainer1.Text = "splitContainer1";
        // 
        // treeOne
        // 
        this.treeOne.Dock = System.Windows.Forms.DockStyle.Left;
        this.treeOne.HideSelection = false;
        this.treeOne.Location = new System.Drawing.Point(0, 0);
        this.treeOne.Name = "treeOne";
        this.treeOne.Size = new System.Drawing.Size(236, 391);
        this.treeOne.TabIndex = 5;
        this.treeOne.DragDrop += new System.Windows.Forms.DragEventHandler(this.tree_DragDrop);
        this.treeOne.DragOver += new System.Windows.Forms.DragEventHandler(this.tree_DragOver);
        this.treeOne.MouseDown += new System.Windows.Forms.MouseEventHandler(this.tree_MouseDown);
        // 
        // treeTwo
        // 
        this.treeTwo.Dock = System.Windows.Forms.DockStyle.Fill;
        this.treeTwo.Location = new System.Drawing.Point(0, 0);
        this.treeTwo.Name = "treeTwo";
        this.treeTwo.Size = new System.Drawing.Size(214, 391);
        this.treeTwo.TabIndex = 7;
        this.treeTwo.DragDrop += new System.Windows.Forms.DragEventHandler(this.tree_DragDrop);
        this.treeTwo.DragOver += new System.Windows.Forms.DragEventHandler(this.tree_DragOver);
        this.treeTwo.MouseDown += new System.Windows.Forms.MouseEventHandler(this.tree_MouseDown);
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(456, 391);
        this.Controls.Add(this.splitContainer1);
        this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.Name = "Form1";
        this.Text = "TreeView Drag-And-Drop";
        this.splitContainer1.Panel1.ResumeLayout(false);
        this.splitContainer1.Panel2.ResumeLayout(false);
        this.splitContainer1.ResumeLayout(false);
        this.ResumeLayout(false);
  }
  [STAThread]
  static void Main()
  {
    Application.EnableVisualStyles();
    Application.Run(new Form1());
  }
}


Get Selected Node Full Path

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
public class Form1 : Form
{
  private System.Windows.Forms.SplitContainer splitContainer1;
  private System.Windows.Forms.TreeView treeOne;
  private System.Windows.Forms.TreeView treeTwo;
  public Form1() {
        InitializeComponent();
    TreeNode node = treeOne.Nodes.Add("A");
    node.Nodes.Add("A1");
    node.Nodes.Add("A2");
    node.Expand();
    node = treeTwo.Nodes.Add("B");
    node.Nodes.Add("B1");
    node.Nodes.Add("B2");
    node.Expand();
  }
    private void tree_DoubleClick(object sender, EventArgs e)
    {
       MessageBox.Show(((TreeView)sender).SelectedNode.FullPath);
    }
  private void InitializeComponent()
  {
        this.splitContainer1 = new System.Windows.Forms.SplitContainer();
        this.treeOne = new System.Windows.Forms.TreeView();
        this.treeTwo = new System.Windows.Forms.TreeView();
        this.splitContainer1.Panel1.SuspendLayout();
        this.splitContainer1.Panel2.SuspendLayout();
        this.splitContainer1.SuspendLayout();
        this.SuspendLayout();
        // 
        // splitContainer1
        // 
        this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.splitContainer1.Location = new System.Drawing.Point(0, 0);
        this.splitContainer1.Name = "splitContainer1";
        // 
        // splitContainer1.Panel1
        // 
        this.splitContainer1.Panel1.Controls.Add(this.treeOne);
        // 
        // splitContainer1.Panel2
        // 
        this.splitContainer1.Panel2.Controls.Add(this.treeTwo);
        this.splitContainer1.Size = new System.Drawing.Size(456, 391);
        this.splitContainer1.SplitterDistance = 238;
        this.splitContainer1.TabIndex = 0;
        this.splitContainer1.Text = "splitContainer1";
        // 
        // treeOne
        // 
        this.treeOne.Dock = System.Windows.Forms.DockStyle.Left;
        this.treeOne.HideSelection = false;
        this.treeOne.Location = new System.Drawing.Point(0, 0);
        this.treeOne.Name = "treeOne";
        this.treeOne.Size = new System.Drawing.Size(236, 391);
        this.treeOne.TabIndex = 5;
        this.treeOne.DoubleClick += new System.EventHandler(this.tree_DoubleClick);
        // 
        // treeTwo
        // 
        this.treeTwo.Dock = System.Windows.Forms.DockStyle.Fill;
        this.treeTwo.Location = new System.Drawing.Point(0, 0);
        this.treeTwo.Name = "treeTwo";
        this.treeTwo.Size = new System.Drawing.Size(214, 391);
        this.treeTwo.TabIndex = 7;
        this.treeTwo.DoubleClick += new System.EventHandler(this.tree_DoubleClick);
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(456, 391);
        this.Controls.Add(this.splitContainer1);
        this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.Name = "Form1";
        this.Text = "TreeView Drag-And-Drop";
        this.splitContainer1.Panel1.ResumeLayout(false);
        this.splitContainer1.Panel2.ResumeLayout(false);
        this.splitContainer1.ResumeLayout(false);
        this.ResumeLayout(false);
  }
  [STAThread]
  static void Main()
  {
    Application.EnableVisualStyles();
    Application.Run(new Form1());
  }
}


Read an XML Document and display the file as a Tree

/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury, 
   Zach Greenvoss, Shripad Kulkarni, Neil Whitlow
Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading ;
using System.Text; 
using System.IO ;
using System.Xml;
//
// Read an XML Document and display the file as a Tree.
//
// Shripad Kulkarni 
// Date : May 15, 2002
// 
namespace XMLTree
{
  /// <summary>
  /// Summary description for XMLTreeForm.
  /// </summary>
  public class XMLTreeForm : System.Windows.Forms.Form
  {
    private System.Windows.Forms.MainMenu mainMenu1;
    private System.Windows.Forms.MenuItem menuItem1;
    private System.Windows.Forms.MenuItem menuItem2;
    private System.Windows.Forms.MenuItem menuItem3;
    private System.Windows.Forms.OpenFileDialog openFileDialog1;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ruponentModel.Container components = null;
    enum VIEW { TREE_VIEW =0} ; 
    string XMLInputFile        = null;
    string FileSize          = "";
    string WorkingDir        = Directory.GetCurrentDirectory(); 
    string OrigFormTitle      = "";
    bool bFileLoaded        = false ;
    int CurrentView          = (int)VIEW.TREE_VIEW ;
    Object NodeTag          = null ;
    Thread t            = null ; 
    TreeNode RootNode        = null ; 
    Point ClickedPoint        = new Point(0,0);
    ArrayList TreeNodeArray      = new ArrayList();
    ImageList tr_il          = new ImageList();
    ImageList tb_il          = new ImageList();
    Bitmap img_fileopen , img_exit , img_collapse , img_expand , img_about;
    
    private System.Windows.Forms.MenuItem menuItem4;
    private System.Windows.Forms.MenuItem menuItem5;
    private System.Windows.Forms.ToolBar toolBar1;
    private System.Windows.Forms.TreeView treeView1;
    private System.Windows.Forms.ToolBarButton Open;
    private System.Windows.Forms.ToolBarButton Exit;
    private System.Windows.Forms.ToolBarButton About;
    private System.Windows.Forms.ToolBarButton SEPARATOR1;
    private System.Windows.Forms.ToolBarButton ExpandAll;
    private System.Windows.Forms.ToolBarButton CollapseAll;
    private System.Windows.Forms.ToolBarButton Stop;
    private System.Windows.Forms.ToolBarButton SEPARATOR2;
    private System.Windows.Forms.ListBox listBox1;
    private System.Windows.Forms.Splitter splitter1;
    private System.Windows.Forms.ToolBarButton SEPARATOR3;
    delegate void MyDelegate();
    public XMLTreeForm()
    {
      InitializeComponent();
    }
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null) 
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }
    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.mainMenu1 = new System.Windows.Forms.MainMenu();
      this.menuItem1 = new System.Windows.Forms.MenuItem();
      this.menuItem3 = new System.Windows.Forms.MenuItem();
      this.menuItem2 = new System.Windows.Forms.MenuItem();
      this.menuItem4 = new System.Windows.Forms.MenuItem();
      this.menuItem5 = new System.Windows.Forms.MenuItem();
      this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
      this.toolBar1 = new System.Windows.Forms.ToolBar();
      this.Open = new System.Windows.Forms.ToolBarButton();
      this.SEPARATOR1 = new System.Windows.Forms.ToolBarButton();
      this.ExpandAll = new System.Windows.Forms.ToolBarButton();
      this.CollapseAll = new System.Windows.Forms.ToolBarButton();
      this.Stop = new System.Windows.Forms.ToolBarButton();
      this.SEPARATOR3 = new System.Windows.Forms.ToolBarButton();
      this.Exit = new System.Windows.Forms.ToolBarButton();
      this.About = new System.Windows.Forms.ToolBarButton();
      this.SEPARATOR2 = new System.Windows.Forms.ToolBarButton();
      this.treeView1 = new System.Windows.Forms.TreeView();
      this.listBox1 = new System.Windows.Forms.ListBox();
      this.splitter1 = new System.Windows.Forms.Splitter();
      this.SuspendLayout();
      // 
      // mainMenu1
      // 
      this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                            this.menuItem1,
                                            this.menuItem4});
      // 
      // menuItem1
      // 
      this.menuItem1.Index = 0;
      this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                            this.menuItem3,
                                            this.menuItem2});
      this.menuItem1.OwnerDraw = true;
      this.menuItem1.Text = "File";
      this.menuItem1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.menuItem1_DrawItem);
      this.menuItem1.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.menuItem1_MeasureItem);
      // 
      // menuItem3
      // 
      this.menuItem3.Index = 0;
      this.menuItem3.OwnerDraw = true;
      this.menuItem3.Text = "Open";
      this.menuItem3.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.menuItem3_DrawItem);
      this.menuItem3.Click += new System.EventHandler(this.menuItem3_Click);
      this.menuItem3.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.menuItem3_MeasureItem);
      // 
      // menuItem2
      // 
      this.menuItem2.Index = 1;
      this.menuItem2.OwnerDraw = true;
      this.menuItem2.Text = "Exit";
      this.menuItem2.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.menuItem3_DrawItem);
      this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
      this.menuItem2.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.menuItem3_MeasureItem);
      // 
      // menuItem4
      // 
      this.menuItem4.Index = 1;
      this.menuItem4.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                            this.menuItem5});
      this.menuItem4.OwnerDraw = true;
      this.menuItem4.Text = "Help";
      this.menuItem4.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.menuItem1_DrawItem);
      this.menuItem4.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.menuItem1_MeasureItem);
      // 
      // menuItem5
      // 
      this.menuItem5.Index = 0;
      this.menuItem5.OwnerDraw = true;
      this.menuItem5.Text = "About";
      this.menuItem5.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.menuItem3_DrawItem);
      this.menuItem5.Click += new System.EventHandler(this.menuItem5_Click);
      this.menuItem5.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.menuItem3_MeasureItem);
      // 
      // openFileDialog1
      // 
      this.openFileDialog1.Filter = "XML FILES| *.xml";
      this.openFileDialog1.FileOk += new System.ruponentModel.CancelEventHandler(this.openFileDialog1_FileOk);
      // 
      // toolBar1
      // 
      this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
      this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
                                            this.Open,
                                            this.SEPARATOR1,
                                            this.ExpandAll,
                                            this.CollapseAll,
                                            this.Stop,
                                            this.SEPARATOR3,
                                            this.Exit,
                                            this.About,
                                            this.SEPARATOR2});
      this.toolBar1.ButtonSize = new System.Drawing.Size(16, 16);
      this.toolBar1.Cursor = System.Windows.Forms.Cursors.Hand;
      this.toolBar1.DropDownArrows = true;
      this.toolBar1.Name = "toolBar1";
      this.toolBar1.ShowToolTips = true;
      this.toolBar1.Size = new System.Drawing.Size(840, 25);
      this.toolBar1.TabIndex = 0;
      this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
      // 
      // Open
      // 
      this.Open.ImageIndex = 0;
      this.Open.ToolTipText = "Open XML File";
      // 
      // SEPARATOR1
      // 
      this.SEPARATOR1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
      // 
      // ExpandAll
      // 
      this.ExpandAll.Enabled = false;
      this.ExpandAll.ImageIndex = 3;
      this.ExpandAll.ToolTipText = "Expand All Nodes";
      // 
      // CollapseAll
      // 
      this.CollapseAll.Enabled = false;
      this.CollapseAll.ImageIndex = 4;
      this.CollapseAll.ToolTipText = "Collapse All Nodes";
      // 
      // Stop
      // 
      this.Stop.Enabled = false;
      this.Stop.ImageIndex = 5;
      this.Stop.ToolTipText = "Stop";
      // 
      // SEPARATOR3
      // 
      this.SEPARATOR3.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
      // 
      // Exit
      // 
      this.Exit.ImageIndex = 1;
      this.Exit.ToolTipText = "Exit Application";
      // 
      // About
      // 
      this.About.ImageIndex = 2;
      this.About.ToolTipText = "Help About";
      // 
      // SEPARATOR2
      // 
      this.SEPARATOR2.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
      // 
      // treeView1
      // 
      this.treeView1.BackColor = System.Drawing.Color.White;
      this.treeView1.Cursor = System.Windows.Forms.Cursors.Hand;
      this.treeView1.Dock = System.Windows.Forms.DockStyle.Left;
      this.treeView1.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
      this.treeView1.FullRowSelect = true;
      this.treeView1.HotTracking = true;
      this.treeView1.ImageIndex = -1;
      this.treeView1.ItemHeight = 16;
      this.treeView1.Location = new System.Drawing.Point(0, 25);
      this.treeView1.Name = "treeView1";
      this.treeView1.SelectedImageIndex = -1;
      this.treeView1.Size = new System.Drawing.Size(360, 472);
      this.treeView1.TabIndex = 3;
      this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
      // 
      // listBox1
      // 
      this.listBox1.Dock = System.Windows.Forms.DockStyle.Fill;
      this.listBox1.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
      this.listBox1.ForeColor = System.Drawing.Color.Maroon;
      this.listBox1.HorizontalScrollbar = true;
      this.listBox1.ItemHeight = 16;
      this.listBox1.Location = new System.Drawing.Point(368, 25);
      this.listBox1.Name = "listBox1";
      this.listBox1.ScrollAlwaysVisible = true;
      this.listBox1.Size = new System.Drawing.Size(472, 468);
      this.listBox1.TabIndex = 12;
      // 
      // splitter1
      // 
      this.splitter1.Location = new System.Drawing.Point(360, 25);
      this.splitter1.Name = "splitter1";
      this.splitter1.Size = new System.Drawing.Size(8, 472);
      this.splitter1.TabIndex = 11;
      this.splitter1.TabStop = false;
      // 
      // XMLTreeForm
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(840, 497);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                      this.listBox1,
                                      this.splitter1,
                                      this.treeView1,
                                      this.toolBar1});
      this.Menu = this.mainMenu1;
      this.Name = "XMLTreeForm";
      this.Text = "XML Viewer";
      this.Resize += new System.EventHandler(this.XMLTreeForm_Resize);
      this.Load += new System.EventHandler(this.XMLTreeForm_Load);
      this.ResumeLayout(false);
    }
    #endregion
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
      Application.Run(new XMLTreeForm());
    }
    private void XMLTreeForm_Load(object sender, System.EventArgs e)
    {
      // Add images to the imageList for treeView
      tr_il.Images.Add(new Icon(WorkingDir+ "\\ROOT.ICO"));    //ROOT    0
      tr_il.Images.Add(new Icon(WorkingDir+ "\\ELEMENT.ICO"));  //ELEMENT  1
      tr_il.Images.Add(new Icon(WorkingDir+ "\\EQUAL.ICO"));    //ATTRIBUTE  2
      treeView1.ImageList = tr_il; 
      // Add images to the imageList for Toolbar
      tb_il.Images.Add(new Bitmap(WorkingDir+ "\\FileOpen.bmp"));    //ROOT    0
      tb_il.Images.Add(new Bitmap(WorkingDir+ "\\exit.bmp"));      //ELEMENT  1
      tb_il.Images.Add(new Bitmap(WorkingDir+ "\\about.bmp"));    //ATTRIBUTE  2
      tb_il.Images.Add(new Bitmap(WorkingDir+ "\\ExpandTree.bmp"));  //ATTRIBUTE  3
      tb_il.Images.Add(new Bitmap(WorkingDir+ "\\CollapseTree.bmp"));  //ATTRIBUTE  4
      tb_il.Images.Add(new Bitmap(WorkingDir+ "\\Stop.bmp"));      //ATTRIBUTE  5
      toolBar1.ImageList = tb_il; 
      // Add images to the imageList for the MenuBar
      img_fileopen  = new Bitmap("FileOpen.bmp"); 
      img_exit    = new Bitmap("exit.bmp"); 
      img_expand    = new Bitmap("ExpandTree.bmp");
      img_collapse  = new Bitmap("CollapseTree.bmp");
      img_about    = new Bitmap("about.bmp"); 
      OrigFormTitle  = this.Text ; 
    }
    private void menuItem3_Click(object sender, System.EventArgs e)
    {
      openFileDialog1.ShowDialog(this);
    }
    private void openFileDialog1_FileOk(object sender, System.ruponentModel.CancelEventArgs e)
    {
      // Initialize Buttons
      EnableDisableControls() ;
      // Initialize All the Arrays
      treeView1.Nodes.Clear() ;
      listBox1.Items.Clear() ;
      TreeNodeArray.Clear();
      bFileLoaded = false ;
      XMLInputFile  = openFileDialog1.FileName ;
      this.Text    = OrigFormTitle + " ..." + XMLInputFile ; 
      openFileDialog1.Dispose() ;
      
      // Get the filename and filesize
      FileInfo f    = new FileInfo(XMLInputFile);
      FileSize    = f.Length.ToString();
      // Begin thread to read input file and load into the ListBox
      Thread t    = new Thread(new ThreadStart(PopulateList));
      t.Start();
      // Begin thread to read input file and populate the Tree
      Thread tt    = new Thread(new ThreadStart(PopulateTree));
      tt.Start();
    }
    private void PopulateList()
    {
      // Load the File
      LoadFileIntoListBox();
    }
  
    private void PopulateTree()
    {
      // TreeView Nodes cannot be added in a thread , until the thread is marshalled
      // using an Invoke or beginInvoke call.
      // We create a delegate ( Funtion Pointer ) and invoke the thread using he delegate
      MyDelegate dlg_obj ;
      dlg_obj = new MyDelegate(ParseFile);  
      treeView1.Invoke(dlg_obj);
    }
    private void ParseFile()
    {
      // Use the XMLReader class to read the XML File and populate the
      // treeview
      try
      {
        XmlTextReader reader    = null;
        reader            = new XmlTextReader(XMLInputFile);
        reader.WhitespaceHandling  = WhitespaceHandling.None;
        string readerName      = "" ;
        bool start_node        = false ;
        int depth          = 0;
        TreeNode WORKINGNODE    = null ; 
        RootNode          = null ; 
        TreeNode AttrNode      = null ;
        TreeNode newNode      = null ;
        bool bIsEmpty        = false ;
        while (reader.Read())
        {
               switch (reader.NodeType)
          {
            case XmlNodeType.Element:
              readerName  = reader.Name;
              bIsEmpty  = reader.IsEmptyElement;
              if ( ! start_node ) 
              { 
                start_node          = true ;
                RootNode          = this.treeView1.Nodes.Add(readerName);
                AssociateTag(RootNode , reader.LineNumber);
                RootNode.SelectedImageIndex  = 0 ;
                RootNode.ImageIndex      = 0 ;
                continue ; 
              }           
              depth = reader.Depth ; 
              if ( reader.IsStartElement() && depth == 1  ) 
              {
                WORKINGNODE = RootNode.Nodes.Add(reader.Name);
                AssociateTag(WORKINGNODE, reader.LineNumber);
              }
              else
              {
                TreeNode parent = WORKINGNODE;
                WORKINGNODE    = parent.Nodes.Add(reader.Name);
                AssociateTag(WORKINGNODE, reader.LineNumber);
              }
              WORKINGNODE.SelectedImageIndex= 1 ;
              WORKINGNODE.ImageIndex= 1 ;
              for (int i = 0; i < reader.AttributeCount; i++)
              {
                reader.MoveToAttribute(i);
                string rValue  = reader.Value.Replace("\r\n", " ");
                AttrNode    = WORKINGNODE.Nodes.Add(reader.Name);
//                AttrNode = WORKINGNODE.Nodes.Add(reader.Name +"="+rValue);
                AssociateTag(AttrNode, reader.LineNumber);
                AttrNode.SelectedImageIndex  = 1 ;
                AttrNode.ImageIndex      = 1 ;
                TreeNode tmp        = AttrNode.Nodes.Add(rValue);
                tmp.SelectedImageIndex    = 2 ;
                tmp.ImageIndex        = 2 ;
                AssociateTag(tmp, reader.LineNumber);
                AttrNode.SelectedImageIndex  = 2 ;
                AttrNode.ImageIndex      = 2 ;
              }
              if ( bIsEmpty ) 
                WORKINGNODE = WORKINGNODE.Parent ; 
              
              break;
            case XmlNodeType.Text:
            {
              string rValue        = reader.Value.Replace("\r\n" , " ");
              newNode            = WORKINGNODE.Nodes.Add(rValue);
              AssociateTag(newNode, reader.LineNumber);
              newNode.SelectedImageIndex  = 2 ;
              newNode.ImageIndex      = 2 ;
            }
              break;
            case XmlNodeType.EndElement:
              WORKINGNODE          = WORKINGNODE.Parent ; 
              break;
          }       
            }           
        reader.Close();
        RootNode.Expand();
      }
      catch(Exception  eee) 
      {
        Console.WriteLine(eee.Message);
      }
    }
    private void treeView1_Click(object sender, System.EventArgs  e)
    {  
    }
    private void treeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
    {
      if ( ! bFileLoaded ) return ; 
      // The treenode is selected. Every node is tagged with LineNumber ( from input file ).
      // This allows us to jump to the line in the file.
      TreeNode tn;
      tn      = (TreeNode)e.Node;
      Object ln  = tn.Tag ; 
      int line  = Convert.ToInt32(ln.ToString());
      MoveToLine(line);
    }
    private void menuItem2_Click(object sender, System.EventArgs e)
    {
      AppExit();
    }
    private void AppExit()
    {
      Application.Exit() ;
    }
    private void LoadFileIntoListBox()
    {
      // Load the xml file into a listbox.
      try
      {
            StreamReader sr = new StreamReader(XMLInputFile, Encoding.ASCII);
        sr.BaseStream.Seek(0, SeekOrigin.Begin);
        while (sr.Peek() > -1) 
        {
               Thread.Sleep(5);
               string str = sr.ReadLine();
          listBox1.Items.Add(str);
        }
        sr.Close();
        bFileLoaded = true ;
        listBox1.SetSelected(1 , true);
      }
      catch(Exception ee)
      {
        Console.WriteLine("Error Reading File into ListBox " + ee.Message);
      }
    }
    private void MoveToLine(int ln)
    {
      // Select the input line from the file in the listbox
      listBox1.SetSelected(ln-1 , true);
    }
    private void AssociateTag(TreeNode t , int l)
    {
      // Associate a line number Tag with every node in the tree
      NodeTag = new Object();
      NodeTag = l ; 
      t.Tag  = NodeTag ; 
    }
    private void menuItem5_Click(object sender, System.EventArgs e)
    {
      // About Box is clicked
      ShowAboutBox();
    }
    private void ShowAboutBox()
    {
      About abt = new About() ;
      abt.ShowDialog() ;
    }
    
    private void EnableDisableControls()
    {
      // Enable Disable Buttons
      switch ( CurrentView ) 
      {
        case 0 :  // TREE VIEW
        {
          ExpandAll.Enabled  = true;
          CollapseAll.Enabled = true;
          Stop.Enabled    = true ;
          treeView1.Visible  = true;
        }
        break ;
        case 1 :  // REPORT VIEW
        {
          ExpandAll.Enabled  = false ;
          CollapseAll.Enabled = false ;
          Stop.Enabled    = false ;
        }
        break ;
      }
    }
    private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
    {
      // Invoke the function upon clicking the toolbar button
      int x = int.Parse(toolBar1.Buttons.IndexOf(e.Button).ToString());
      switch(toolBar1.Buttons.IndexOf(e.Button))
      {
        case 0:
          openFileDialog1.ShowDialog(this);
          break; 
        case 1:   
          //separator
          break; 
        case 2:
          TExpandAll() ;
          break; 
        case 3:
          TCollapseAll();          
          break; 
        case 4:
          if ( t != null && t.IsAlive ) 
          {
            t.Abort() ;
            t = null ; 
            EnableDisableControls();
          }
          break; 
        case 5:
          break; 
        case 6:
          AppExit();
          break; 
        case 7:
          ShowAboutBox();
          break; 
        case 8:  // separator
          //separator
          break; 
        case 9:  // Go Back 
          break; 
        case 10:// separator
          break; 
        case 11:// Go Back 
          CurrentView = (int)VIEW.TREE_VIEW ;
          EnableDisableControls();
          break; 
      }
    }
    private void TExpandAll()
    {
      t = new Thread(new ThreadStart(TE));
      t.Start();
    }
    
    private void TE()
    {
      // Expand all nodes in the tree
      treeView1.ExpandAll() ;
    }
    private void TCollapseAll()
    {
      // Collapse all nodes in the tree
      treeView1.CollapseAll() ;
    }
    void Clear()
    {
      TreeNodeArray.Clear();
    }
    private void menuItem1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
    {  
      //Owner Draw Menu Items
      //Get the bounding rectangle
      Rectangle rc = new Rectangle(e.Bounds.X+1 , e.Bounds.Y+1, e.Bounds.Width-5, e.Bounds.Height-1);
      //Fill the rectangle
      e.Graphics.FillRectangle(new SolidBrush(Color.LightGray) , rc);
      //Unbox the menu item
      MenuItem s = (MenuItem)sender ;
      string s1 = s.Text ;
      //Set the stringformat object
      StringFormat sf = new StringFormat();
      sf.Alignment = StringAlignment.Center ;
      e.Graphics.DrawString(s1 , new Font("Ariel" ,10), new SolidBrush(Color.Black) , rc , sf );
      Console.WriteLine(e.State.ToString());
      //Check if the object is selected. 
      if ( e.State ==  (DrawItemState.NoAccelerator | DrawItemState.Selected)  ||  
        e.State ==  ( DrawItemState.NoAccelerator | DrawItemState.HotLight)  ) 
      {
        // Draw selected menu item
        e.Graphics.FillRectangle(new SolidBrush(Color.LightYellow) , rc);
        e.Graphics.DrawString( s1 , new Font("Veranda" , 10 , FontStyle.Bold  ) , new SolidBrush(Color.Red), rc ,sf);
        e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.Black)), rc );
      }
      e.DrawFocusRectangle();
      e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.Black), 1 ), rc );
    }
    private void menuItem1_MeasureItem(object sender, System.Windows.Forms.MeasureItemEventArgs e)
    {
      // Set the menu item height
      e.ItemWidth = 75 ;  
    }
    private void menuItem3_MeasureItem(object sender, System.Windows.Forms.MeasureItemEventArgs e)
    {
      // Set the sub menu item height and width
      e.ItemWidth = 95 ;
      e.ItemHeight = 25 ;    
    }
    private void menuItem3_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
    {
      //Owner Draw Sub Menu Items
      Rectangle rc = new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);
      e.Graphics.FillRectangle(new SolidBrush(Color.LightGray) , rc);
      MenuItem s = (MenuItem)sender ;
      string s1 = s.Text ;
      StringFormat sf = new StringFormat();
      sf.Alignment = StringAlignment.Far ;
      sf.LineAlignment  = StringAlignment.Center;

      Image useImage = null ;
      if ( s1 == "Open" ) 
      {
        useImage = img_fileopen;
      }
      if ( s1 == "ExpandAll" )
      {
        if ( CurrentView == (int)VIEW.TREE_VIEW ) 
          s.Enabled = true;
        else
          s.Enabled = false ;
        useImage = img_expand;
      }
      if ( s1 == "Exit" )
      {
        useImage = img_exit;
      }
      if ( s1 == "CollapseAll" )
      {
        if ( CurrentView == (int)VIEW.TREE_VIEW ) 
          s.Enabled = true;
        else
          s.Enabled = false ;
        useImage = img_collapse;
      }
      if ( s1 == "About" )
      {
        useImage = img_about;
      }
      Rectangle rcText = rc ;
      rcText.Width-=5 ;
      e.Graphics.DrawString(s1 , new Font("Veranda" ,10), new SolidBrush(Color.Blue) , rcText, sf );
      e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.LightGray)), rc );
      if ( e.State == ( DrawItemState.NoAccelerator | DrawItemState.Selected)) 
      {
        Rectangle rc1= rc ;
        rc1.X = rc1.X + useImage.Width + 5 ;
        rc1.Width = rc.Width - 25 ;
        rc1.Height = rc.Height- 2 ;
        e.Graphics.FillRectangle(new SolidBrush(Color.LightYellow) , rc);
        e.Graphics.DrawString( s1 , new Font("Veranda" , 10 , FontStyle.Bold | FontStyle.Underline) , new SolidBrush(Color.Red), rcText,sf);
        e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.Black),3), rc );
        e.DrawFocusRectangle();
      }
      if ( useImage != null ) 
      {
        SizeF sz = useImage.PhysicalDimension;
        e.Graphics.DrawImage(useImage, e.Bounds.X+5 , ( e.Bounds.Bottom + e.Bounds.Top ) /2 - sz.Height/2);
      }  
    }
    private void XMLTreeForm_Resize(object sender, System.EventArgs e)
    {
    }
  }
}

<A href="http://www.nfex.ru/Code/CSharpDownload/XMLTree.zip">XMLTree.zip( 85 k)</a>


Recursively load Directory info into TreeView

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
public class Form1 : Form
{
      private System.Windows.Forms.TreeView directoryTreeView;
     
      string substringDirectory;
       
      public Form1() {
        InitializeComponent();
        directoryTreeView.Nodes.Clear();
        
        String path = "c:\\Temp";
        directoryTreeView.Nodes.Add( path );
        PopulateTreeView(path, directoryTreeView.Nodes[ 0 ] );
      }  
      public void PopulateTreeView(string directoryValue, TreeNode parentNode )
      {
          string[] directoryArray = 
           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
      }
      private void InitializeComponent()
      {
         this.directoryTreeView = new System.Windows.Forms.TreeView();
         this.SuspendLayout();
         // 
         // directoryTreeView
         // 
         this.directoryTreeView.Location = new System.Drawing.Point(12, 77);
         this.directoryTreeView.Name = "directoryTreeView";
         this.directoryTreeView.Size = new System.Drawing.Size(284, 265);
         this.directoryTreeView.TabIndex = 0;
         // 
         // TreeViewDirectoryStructureForm
         // 
         this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
         this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
         this.ClientSize = new System.Drawing.Size(304, 354);
         this.Controls.Add(this.directoryTreeView);
         this.Name = "TreeViewDirectoryStructureForm";
         this.Text = "TreeViewDirectoryStructure";
         this.ResumeLayout(false);
         this.PerformLayout();
      }
  [STAThread]
  static void Main()
  {
    Application.EnableVisualStyles();
    Application.Run(new Form1());
  }
}


Subclass TreeView

 
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
   
class DirectoryTreeView: TreeView
{
     public DirectoryTreeView()
     {
          ImageList = new ImageList();
          ImageList.Images.Add(new Bitmap(GetType(), "FLOPPY.BMP"));
          ImageList.Images.Add(new Bitmap(GetType(), "FOLD.BMP"));
          ImageList.Images.Add(new Bitmap(GetType(), "OPENFOLD.BMP"));
          RefreshTree();
     }
     public void RefreshTree()
     {
          BeginUpdate();
          Nodes.Clear();
          string[] astrDrives = Directory.GetLogicalDrives();
   
          foreach (string str in astrDrives)
          {
               TreeNode tnDrive = new TreeNode(str, 0, 0);
               Nodes.Add(tnDrive);
               AddDirectories(tnDrive);
   
               if (str == "C:\\")
                    SelectedNode = tnDrive;
          }
          EndUpdate();
     }
     void AddDirectories(TreeNode tn)
     {
          tn.Nodes.Clear();
   
          string          strPath = tn.FullPath;
          DirectoryInfo   dirinfo = new DirectoryInfo(strPath);
          DirectoryInfo[] adirinfo;
   
          adirinfo = dirinfo.GetDirectories();
   
          foreach (DirectoryInfo di in adirinfo)
          {
               TreeNode tnDir = new TreeNode(di.Name, 1, 2);
               tn.Nodes.Add(tnDir);
          }
     }
     protected override void OnBeforeExpand(TreeViewCancelEventArgs tvcea)
     {
          base.OnBeforeExpand(tvcea);
   
          BeginUpdate();
   
          foreach (TreeNode tn in tvcea.Node.Nodes)
               AddDirectories(tn);
   
          EndUpdate();
     }
}
class DirectoriesAndFiles: Form
{
     DirectoryTreeView dirtree;
     Panel             panel;
     TreeNode          tnSelect;
   
     public static void Main()
     {
          Application.Run(new DirectoriesAndFiles());
     }
     public DirectoriesAndFiles()
     {
          Text = "Directories and Files";
          BackColor = SystemColors.Window;
          ForeColor = SystemColors.WindowText;
   
          panel = new Panel();
          panel.Parent = this;
          panel.Dock = DockStyle.Fill;
          panel.Paint += new PaintEventHandler(PanelOnPaint);
   
          Splitter split = new Splitter();
          split.Parent = this;
          split.Dock = DockStyle.Left;
          split.BackColor = SystemColors.Control;
   
          dirtree = new DirectoryTreeView();
          dirtree.Parent = this;
          dirtree.Dock = DockStyle.Left;
          dirtree.AfterSelect += new TreeViewEventHandler(DirectoryTreeViewOnAfterSelect);
   
          Menu = new MainMenu();
          Menu.MenuItems.Add("View");
   
          MenuItem mi = new MenuItem("Refresh", new EventHandler(MenuOnRefresh), Shortcut.F5);
          Menu.MenuItems[0].MenuItems.Add(mi);
     }
     void DirectoryTreeViewOnAfterSelect(object obj, TreeViewEventArgs tvea)
     {
          tnSelect = tvea.Node;
          panel.Invalidate();
     }
     void PanelOnPaint(object obj, PaintEventArgs pea)
     {
          if (tnSelect == null)
               return;
   
          Panel         panel     = (Panel) obj;
          Graphics      grfx      = pea.Graphics;
          DirectoryInfo dirinfo   = new DirectoryInfo(tnSelect.FullPath);
          FileInfo[]    afileinfo;
          Brush         brush     = new SolidBrush(panel.ForeColor);
          int           y         = 0;
   
          afileinfo = dirinfo.GetFiles();
          foreach (FileInfo fileinfo in afileinfo)
          {
               grfx.DrawString(fileinfo.Name, Font, brush, 0, y);
               y += Font.Height;
          }
     }
     void MenuOnRefresh(object obj, EventArgs ea)
     {
          dirtree.RefreshTree();
     }
}


TreeView Data Binding

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald
Publisher: Apress
ISBN: 1590590457
*/
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace TreeViewDataBinding
{
  /// <summary>
  /// Summary description for TreeViewDataBinding.
  /// </summary>
  public class TreeViewDataBinding : System.Windows.Forms.Form
  {
    internal System.Windows.Forms.Panel Panel2;
    internal System.Windows.Forms.Panel Panel3;
    internal System.Windows.Forms.Label lblInfo;
    internal System.Windows.Forms.Label Label1;
    internal System.Windows.Forms.Splitter Splitter1;
    internal System.Windows.Forms.TreeView treeDB;
    internal System.Windows.Forms.Panel Panel1;
    internal System.Windows.Forms.Button cmdClose;
    internal System.Windows.Forms.GroupBox GroupBox1;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ruponentModel.Container components = null;
    public TreeViewDataBinding()
    {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();
      //
      // TODO: Add any constructor code after InitializeComponent call
      //
    }
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null) 
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }
    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.Panel2 = new System.Windows.Forms.Panel();
      this.Panel3 = new System.Windows.Forms.Panel();
      this.lblInfo = new System.Windows.Forms.Label();
      this.Label1 = new System.Windows.Forms.Label();
      this.Splitter1 = new System.Windows.Forms.Splitter();
      this.treeDB = new System.Windows.Forms.TreeView();
      this.Panel1 = new System.Windows.Forms.Panel();
      this.cmdClose = new System.Windows.Forms.Button();
      this.GroupBox1 = new System.Windows.Forms.GroupBox();
      this.Panel2.SuspendLayout();
      this.Panel3.SuspendLayout();
      this.Panel1.SuspendLayout();
      this.SuspendLayout();
      // 
      // Panel2
      // 
      this.Panel2.Controls.AddRange(new System.Windows.Forms.Control[] {
                                         this.Panel3,
                                         this.Splitter1,
                                         this.treeDB});
      this.Panel2.Dock = System.Windows.Forms.DockStyle.Fill;
      this.Panel2.Location = new System.Drawing.Point(5, 5);
      this.Panel2.Name = "Panel2";
      this.Panel2.Size = new System.Drawing.Size(446, 264);
      this.Panel2.TabIndex = 8;
      // 
      // Panel3
      // 
      this.Panel3.Controls.AddRange(new System.Windows.Forms.Control[] {
                                         this.lblInfo,
                                         this.Label1});
      this.Panel3.Dock = System.Windows.Forms.DockStyle.Fill;
      this.Panel3.Location = new System.Drawing.Point(239, 0);
      this.Panel3.Name = "Panel3";
      this.Panel3.Size = new System.Drawing.Size(207, 264);
      this.Panel3.TabIndex = 7;
      // 
      // lblInfo
      // 
      this.lblInfo.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right);
      this.lblInfo.BackColor = System.Drawing.SystemColors.Window;
      this.lblInfo.Location = new System.Drawing.Point(16, 12);
      this.lblInfo.Name = "lblInfo";
      this.lblInfo.Size = new System.Drawing.Size(176, 240);
      this.lblInfo.TabIndex = 1;
      // 
      // Label1
      // 
      this.Label1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right);
      this.Label1.BackColor = System.Drawing.SystemColors.Window;
      this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
      this.Label1.Location = new System.Drawing.Point(4, 0);
      this.Label1.Name = "Label1";
      this.Label1.Size = new System.Drawing.Size(200, 264);
      this.Label1.TabIndex = 2;
      // 
      // Splitter1
      // 
      this.Splitter1.Location = new System.Drawing.Point(236, 0);
      this.Splitter1.Name = "Splitter1";
      this.Splitter1.Size = new System.Drawing.Size(3, 264);
      this.Splitter1.TabIndex = 6;
      this.Splitter1.TabStop = false;
      // 
      // treeDB
      // 
      this.treeDB.Dock = System.Windows.Forms.DockStyle.Left;
      this.treeDB.ImageIndex = -1;
      this.treeDB.Name = "treeDB";
      this.treeDB.SelectedImageIndex = -1;
      this.treeDB.Size = new System.Drawing.Size(236, 264);
      this.treeDB.TabIndex = 4;
      this.treeDB.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeDB_AfterSelect);
      this.treeDB.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.treeDB_BeforeExpand);
      // 
      // Panel1
      // 
      this.Panel1.Controls.AddRange(new System.Windows.Forms.Control[] {
                                         this.cmdClose,
                                         this.GroupBox1});
      this.Panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
      this.Panel1.Location = new System.Drawing.Point(5, 269);
      this.Panel1.Name = "Panel1";
      this.Panel1.Size = new System.Drawing.Size(446, 36);
      this.Panel1.TabIndex = 7;
      // 
      // cmdClose
      // 
      this.cmdClose.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
      this.cmdClose.FlatStyle = System.Windows.Forms.FlatStyle.System;
      this.cmdClose.Location = new System.Drawing.Point(372, 12);
      this.cmdClose.Name = "cmdClose";
      this.cmdClose.Size = new System.Drawing.Size(72, 24);
      this.cmdClose.TabIndex = 4;
      this.cmdClose.Text = "Close";
      this.cmdClose.Click += new System.EventHandler(this.cmdClose_Click);
      // 
      // GroupBox1
      // 
      this.GroupBox1.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right);
      this.GroupBox1.Name = "GroupBox1";
      this.GroupBox1.Size = new System.Drawing.Size(444, 8);
      this.GroupBox1.TabIndex = 5;
      this.GroupBox1.TabStop = false;
      // 
      // TreeViewDataBinding
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
      this.ClientSize = new System.Drawing.Size(456, 310);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                      this.Panel2,
                                      this.Panel1});
      this.DockPadding.All = 5;
      this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
      this.Name = "TreeViewDataBinding";
      this.Text = "TreeViewDataBinding";
      this.Load += new System.EventHandler(this.TreeViewDataBinding_Load);
      this.Panel2.ResumeLayout(false);
      this.Panel3.ResumeLayout(false);
      this.Panel1.ResumeLayout(false);
      this.ResumeLayout(false);
    }
    #endregion
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
      Application.Run(new TreeViewDataBinding());
    }
    private ProductDatabase DataClass = new ProductDatabase();
    private void TreeViewDataBinding_Load(object sender, System.EventArgs e)
    {
      TreeNode nodeParent;
      foreach (DataRow row in DataClass.GetCategories().Rows)
      {
        // Add the category node.
        nodeParent = treeDB.Nodes.Add(row[ProductDatabase.CategoryField.Name].ToString());
        nodeParent.ImageIndex = 0;
        // Store the disconnected category information.
        nodeParent.Tag = row;
        // Add a "dummy" node.
        nodeParent.Nodes.Add("*");
      }
    
    }
    private void treeDB_BeforeExpand(object sender, System.Windows.Forms.TreeViewCancelEventArgs e)
    {
      TreeNode nodeSelected, nodeChild;
      nodeSelected = e.Node;
      if (nodeSelected.Nodes[0].Text == "*")
      {
        // This is a dummy node.
        nodeSelected.Nodes.Clear();
        foreach (DataRow row in
          DataClass.GetProductsInCategory((DataRow)nodeSelected.Tag))
        {
          nodeChild = nodeSelected.Nodes.Add(row[ProductDatabase.ProductField.Name].ToString());
          // Store the disconnected product information.
          nodeChild.Tag = row;
          nodeChild.ImageIndex = 1;
          nodeChild.SelectedImageIndex = 1;
        }
      }
    }
    private void treeDB_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
    {
       lblInfo.Text = DataClass.GetDisplayText((DataRow)e.Node.Tag);
    }
    private void cmdClose_Click(object sender, System.EventArgs e)
    {
      this.Close();
    }
  }

  public class ProductDatabase
  {
    public class Tables
    {
      public const string Product = "Products";
      public const string Category = "Categories";
    }
    public class ProductField
    {
      public const string Name = "ModelName";
      public const string Description = "Description";
    }
    public class CategoryField
    {
      public const string Name = "CategoryName";
    }
    private DataSet dsStore;
    DataRelation relCategoryProduct;
    public ProductDatabase()
    {
      dsStore = new DataSet();
      dsStore.ReadXmlSchema(Application.StartupPath + "\\store.xsd");
      dsStore.ReadXml(Application.StartupPath + "\\store.xml");
      // Define the relation.
      relCategoryProduct = new DataRelation("Prod_Cat", 
        dsStore.Tables["Categories"].Columns["CategoryID"], 
        dsStore.Tables["Products"].Columns["CategoryID"]);
      dsStore.Relations.Add(relCategoryProduct);
    }
    public DataTable GetCategories()
    {
      return dsStore.Tables["Categories"];
    }
    public DataRow[] GetProductsInCategory(DataRow rowParent)
    {
      return rowParent.GetChildRows(relCategoryProduct);
    }
    public string GetDisplayText(DataRow row)
    {
      string text = "";
      switch (row.Table.TableName)
      {
        case Tables.Product:
          text = "ID: " + row[0] + "\n";
          text += "Name: " + row[ProductField.Name] + "\n\n";
          text += row[ProductField.Description];
          break;
      }
      return text;
    }
  }
}

<A href="http://www.nfex.ru/Code/CSharpDownload/TreeViewDataBinding.zip">TreeViewDataBinding.zip( 56 k)</a>


TreeView Demo

/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury, 
   Zach Greenvoss, Shripad Kulkarni, Neil Whitlow
Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace TreeView
{
  /// <summary>
  /// Summary description for TreeViewDemo.
  /// </summary>
  public class TreeViewDemo : System.Windows.Forms.Form
  {
    private System.Windows.Forms.TreeView treeView1;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ruponentModel.Container components = null;
    ImageList il = new ImageList();
    public TreeViewDemo()
    {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();
      //
      // TODO: Add any constructor code after InitializeComponent call
      //
    }
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null) 
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }
    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
         this.treeView1 = new System.Windows.Forms.TreeView();
         this.SuspendLayout();
         // 
         // treeView1
         // 
         this.treeView1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right);
         this.treeView1.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
         this.treeView1.HotTracking = true;
         this.treeView1.ImageIndex = -1;
         this.treeView1.Indent = 30;
         this.treeView1.ItemHeight = 30;
         this.treeView1.LabelEdit = true;
         this.treeView1.Location = new System.Drawing.Point(8, 16);
         this.treeView1.Name = "treeView1";
         this.treeView1.SelectedImageIndex = -1;
         this.treeView1.Size = new System.Drawing.Size(360, 272);
         this.treeView1.TabIndex = 0;
         // 
         // TreeViewDemo
         // 
         this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
         this.ClientSize = new System.Drawing.Size(376, 309);
         this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                      this.treeView1});
         this.Name = "TreeViewDemo";
         this.Text = "TreeView Control";
         this.Load += new System.EventHandler(this.TreeViewDemo_Load);
         this.ResumeLayout(false);
      }
    #endregion
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
      Application.Run(new TreeViewDemo());
    }
    private void TreeViewDemo_Load(object sender, System.EventArgs e)
    {
      // Select icons into the image list
      il.Images.Add(new Icon("KEY04.ICO"));
      il.Images.Add(new Icon("ARW06LT.ICO"));
      il.Images.Add(new Icon("LITENING.ICO"));
      il.Images.Add(new Icon("ARW06UP.ICO"));
      treeView1.ImageList = il ; 
  
      // Create the RootNode
      TreeNode rootNode = treeView1.Nodes.Add("USA");
      rootNode.ImageIndex =0 ;
      // Create the Child nodes for the root
      TreeNode states1 = rootNode.Nodes.Add("New York");
      states1.ImageIndex =1 ;
      TreeNode states2 = rootNode.Nodes.Add("Michigan");
      states2.ImageIndex =1 ;
      TreeNode states3 = rootNode.Nodes.Add("Wisconsin");
      states3.ImageIndex =1 ;
      TreeNode states4 = rootNode.Nodes.Add("California");
      states4.ImageIndex =1 ;
      // Create siblings nodes for the Child nodes 
      TreeNode child = states1.Nodes.Add("Rochester");
      child.ImageIndex = 2 ;
      child =states1.Nodes.Add("new York");
      child.ImageIndex = 2 ;
      child =states1.Nodes.Add("Albany");
      child.ImageIndex = 2 ;
      child = states2.Nodes.Add("Detroit");
      child.ImageIndex = 2 ;
      child =states2.Nodes.Add("Ann Arbor");
      child.ImageIndex = 2 ;
      child =states2.Nodes.Add("Lansing");
      child.ImageIndex = 2 ;
      child = states3.Nodes.Add("Milwaukee");
      child.ImageIndex = 2 ;
      child =states3.Nodes.Add("Madison");
      child.ImageIndex = 2 ;
      child =states3.Nodes.Add("La Cross");
      child.ImageIndex = 2 ;
    
      child = states4.Nodes.Add("Los Angeles");
      child.ImageIndex = 2 ;
      child =states4.Nodes.Add("San Fransisco");
      child.ImageIndex = 2 ;
      child =states4.Nodes.Add("San Diego");
      child.ImageIndex = 2 ;
    }
  }
}

<A href="http://www.nfex.ru/Code/CSharpDownload/TreeView.zip">TreeView.zip( 32 k)</a>


TreeView Drag And Drop

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald
Publisher: Apress
ISBN: 1590590457
*/
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace TreeViewDragAndDrop
{
    /// <summary>
    /// Summary description for TreeViewDragAndDrop.
    /// </summary>
    public class TreeViewDragAndDrop : System.Windows.Forms.Form
    {
        internal System.Windows.Forms.TreeView treeTwo;
        internal System.Windows.Forms.Splitter Splitter1;
        internal System.Windows.Forms.TreeView treeOne;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ruponentModel.Container components = null;
        public TreeViewDragAndDrop()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.treeTwo = new System.Windows.Forms.TreeView();
            this.Splitter1 = new System.Windows.Forms.Splitter();
            this.treeOne = new System.Windows.Forms.TreeView();
            this.SuspendLayout();
            // 
            // treeTwo
            // 
            this.treeTwo.Dock = System.Windows.Forms.DockStyle.Fill;
            this.treeTwo.HideSelection = false;
            this.treeTwo.ImageIndex = -1;
            this.treeTwo.Location = new System.Drawing.Point(239, 0);
            this.treeTwo.Name = "treeTwo";
            this.treeTwo.SelectedImageIndex = -1;
            this.treeTwo.Size = new System.Drawing.Size(281, 366);
            this.treeTwo.TabIndex = 6;
            this.treeTwo.MouseDown += new System.Windows.Forms.MouseEventHandler(this.tree_MouseDown);
            this.treeTwo.DragOver += new System.Windows.Forms.DragEventHandler(this.tree_DragOver);
            this.treeTwo.DragDrop += new System.Windows.Forms.DragEventHandler(this.tree_DragDrop);
            // 
            // Splitter1
            // 
            this.Splitter1.Location = new System.Drawing.Point(236, 0);
            this.Splitter1.Name = "Splitter1";
            this.Splitter1.Size = new System.Drawing.Size(3, 366);
            this.Splitter1.TabIndex = 5;
            this.Splitter1.TabStop = false;
            // 
            // treeOne
            // 
            this.treeOne.Dock = System.Windows.Forms.DockStyle.Left;
            this.treeOne.HideSelection = false;
            this.treeOne.ImageIndex = -1;
            this.treeOne.Name = "treeOne";
            this.treeOne.SelectedImageIndex = -1;
            this.treeOne.Size = new System.Drawing.Size(236, 366);
            this.treeOne.TabIndex = 4;
            this.treeOne.MouseDown += new System.Windows.Forms.MouseEventHandler(this.tree_MouseDown);
            this.treeOne.DragOver += new System.Windows.Forms.DragEventHandler(this.tree_DragOver);
            this.treeOne.DragDrop += new System.Windows.Forms.DragEventHandler(this.tree_DragDrop);
            // 
            // TreeViewDragAndDrop
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
            this.ClientSize = new System.Drawing.Size(520, 366);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.treeTwo,
                                                                          this.Splitter1,
                                                                          this.treeOne});
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.Name = "TreeViewDragAndDrop";
            this.Text = "TreeView Drag-And-Drop";
            this.Load += new System.EventHandler(this.TreeViewDragAndDrop_Load);
            this.ResumeLayout(false);
        }
        #endregion
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new TreeViewDragAndDrop());
        }
        private void TreeViewDragAndDrop_Load(object sender, System.EventArgs e)
        {
            TreeNode node = treeOne.Nodes.Add("Fruits");
            node.Nodes.Add("Apple");
            node.Nodes.Add("Peach");
            node.Expand();
            
            node = treeTwo.Nodes.Add("Vegetables");
            node.Nodes.Add("Tomato");
            node.Nodes.Add("Eggplant");
            node.Expand();
            
            treeTwo.AllowDrop = true;
            treeOne.AllowDrop = true;
        }
        private void tree_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) 
        {
            // Get the tree.
            TreeView tree = (TreeView)sender;
            // Get the node underneath the mouse.
            TreeNode node = tree.GetNodeAt(e.X, e.Y);
            tree.SelectedNode = node;
            // Start the drag-and-drop operation with a cloned copy of the node.
            if (node != null)
            {
                tree.DoDragDrop(node.Clone(), DragDropEffects.Copy);
            }
        }
        private void tree_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
        {
            // Get the tree.
            TreeView tree = (TreeView)sender;
            // Drag and drop denied by default.
            e.Effect = DragDropEffects.None;
            // Is it a valid format?
            if (e.Data.GetData(typeof(TreeNode)) != null)
            {
                // Get the screen point.
                Point pt = new Point(e.X, e.Y);
                // Convert to a point in the TreeView"s coordinate system.
                pt = tree.PointToClient(pt);
                // Is the mouse over a valid node?
                TreeNode node = tree.GetNodeAt(pt);
                if (node != null)
                {
                    e.Effect = DragDropEffects.Copy;
                    tree.SelectedNode = node;
                }
            }
        }
        private void tree_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {
            // Get the tree.
            TreeView tree = (TreeView)sender;
            // Get the screen point.
            Point pt = new Point(e.X, e.Y);
            // Convert to a point in the TreeView"s coordinate system.
            pt = tree.PointToClient(pt);
            // Get the node underneath the mouse.
            TreeNode node = tree.GetNodeAt(pt);
            // Add a child node.
            node.Nodes.Add((TreeNode)e.Data.GetData(typeof(TreeNode)));
            // Show the newly added node if it is not already visible.
            node.Expand();
        }
    }
}


TreeView Example

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald
Publisher: Apress
ISBN: 1590590457
*/
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace TreeViewExample
{
    /// <summary>
    /// Summary description for TreeViewExample.
    /// </summary>
    public class TreeViewExample : System.Windows.Forms.Form
    {
        internal System.Windows.Forms.TreeView treeFood;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ruponentModel.Container components = null;
        public TreeViewExample()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.treeFood = new System.Windows.Forms.TreeView();
            this.SuspendLayout();
            // 
            // treeFood
            // 
            this.treeFood.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
                | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);
            this.treeFood.ImageIndex = -1;
            this.treeFood.Location = new System.Drawing.Point(4, 5);
            this.treeFood.Name = "treeFood";
            this.treeFood.SelectedImageIndex = -1;
            this.treeFood.Size = new System.Drawing.Size(284, 256);
            this.treeFood.TabIndex = 1;
            this.treeFood.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeFood_AfterSelect);
            // 
            // TreeViewExample
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.treeFood});
            this.Name = "TreeViewExample";
            this.Text = "TreeView Example";
            this.Load += new System.EventHandler(this.TreeViewExample_Load);
            this.ResumeLayout(false);
        }
        #endregion
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new TreeViewExample());
        }
        private void TreeViewExample_Load(object sender, System.EventArgs e)
        {
            TreeNode node;
            
            node = treeFood.Nodes.Add("Fruits");
            node.Nodes.Add("Apple");
            node.Nodes.Add("Peach");
            
            node = treeFood.Nodes.Add("Vegetables");
            node.Nodes.Add("Tomato");
            node.Nodes.Add("Eggplant");
        }
        private void treeFood_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
        {
            if (e.Action == TreeViewAction.ByMouse)
            {
                MessageBox.Show(e.Node.FullPath);
            }
        }
    }
}


TreeView ImageIndex

 
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class Form1 : System.Windows.Forms.Form {
    private System.Windows.Forms.TreeView treeView1;
    ImageList il = new ImageList();
    public Form1() {
        this.treeView1 = new System.Windows.Forms.TreeView();
        this.SuspendLayout();
        this.treeView1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
           | System.Windows.Forms.AnchorStyles.Left)
           | System.Windows.Forms.AnchorStyles.Right);
        this.treeView1.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
        this.treeView1.HotTracking = true;
        this.treeView1.ImageIndex = -1;
        this.treeView1.Indent = 30;
        this.treeView1.ItemHeight = 30;
        this.treeView1.LabelEdit = true;
        this.treeView1.Location = new System.Drawing.Point(8, 16);
        this.treeView1.SelectedImageIndex = -1;
        this.treeView1.Size = new System.Drawing.Size(360, 272);
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(376, 309);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                      this.treeView1});
        this.Text = "TreeView Control";
        this.Load += new System.EventHandler(this.Form1_Load);
        this.ResumeLayout(false);
    }
    [STAThread]
    static void Main() {
        Application.Run(new Form1());
    }
    private void Form1_Load(object sender, System.EventArgs e) {
        il.Images.Add(new Icon("1.ICO"));
        il.Images.Add(new Icon("2.ICO"));
        il.Images.Add(new Icon("3.ICO"));
        il.Images.Add(new Icon("4.ICO"));
        treeView1.ImageList = il;
        TreeNode rootNode = treeView1.Nodes.Add("USA");
        rootNode.ImageIndex = 0;
        TreeNode states1 = rootNode.Nodes.Add("a");
        states1.ImageIndex = 1;
        TreeNode states2 = rootNode.Nodes.Add("b");
        states2.ImageIndex = 1;
        TreeNode states3 = rootNode.Nodes.Add("c");
        states3.ImageIndex = 1;
        TreeNode states4 = rootNode.Nodes.Add("d");
        states4.ImageIndex = 1;
        TreeNode child = states1.Nodes.Add("A");
        child.ImageIndex = 2;
        child = states1.Nodes.Add("e");
        child.ImageIndex = 2;
        child = states1.Nodes.Add("f");
        child.ImageIndex = 2;
        child = states2.Nodes.Add("g");
        child.ImageIndex = 2;
        child = states2.Nodes.Add("h");
        child.ImageIndex = 2;
        child = states2.Nodes.Add("i");
        child.ImageIndex = 2;
        child = states3.Nodes.Add("j");
        child.ImageIndex = 2;
        child = states3.Nodes.Add("k");
        child.ImageIndex = 2;
        child = states3.Nodes.Add("l");
        child.ImageIndex = 2;
        child = states4.Nodes.Add("m");
        child.ImageIndex = 2;
        child = states4.Nodes.Add("n");
        child.ImageIndex = 2;
        child = states4.Nodes.Add("o");
        child.ImageIndex = 2;
    }
}