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"); } }
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(); } }
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.ComponentModel; 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.ComponentModel.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; } } }
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.ComponentModel; 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.ComponentModel.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 ; } } } TreeView.zip( 32 k)
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.ComponentModel; 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.ComponentModel.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] + " "; text += "Name: " + row[ProductField.Name] + " "; text += row[ProductField.Description]; break; } return text; } } } TreeViewDataBinding.zip( 56 k)
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.ComponentModel; 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.ComponentModel.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.ComponentModel; 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.ComponentModel.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); } } } }