DotNetCurry Logo

Windows Forms 2.0 – TreeView Control Recipes

Posted by: Suprotim Agarwal , on 3/25/2007, in Category WinForms & WinRT
Views: 25053
Abstract: In this article, we will explore how to perform some common tasks using the TreeView Control of Windows Forms 2.0.
Windows Forms 2.0 –TreeView Control Recipes
 
The System.Windows.Forms.TreeView control allows you to visually display a hierarchy of nodes. This is similar to the directory structure displayed by Windows Explorer in its left pane. You can expand and collapse nodes. The TreeView control uses TreeNode objects to represent the items it contains.
How Do I Get Started With The TreeView Control
 
Let us see an example of creating the treeview control :
 
private void CreateTreeViewControl()
{
tvTree = new TreeView();
tvTree.Location = new Point(12, 42);
tvTree.Size = new Size(150, 180);
tvTree.AllowDrop = true;
//tvTree.HideSelection = false;
Controls.Add(tvTree);
}
 
 
 
private void btnLoad_Click(object sender, EventArgs e)
{
tvTree.BeginUpdate();
tvTree.Nodes.Add("Country"); // Parent Node
tvTree.Nodes[0].Nodes.Add("State1");
//Add a State to the Country Node
tvTree.Nodes[0].Nodes.Add("State2");
tvTree.Nodes[0].Nodes[1].Nodes.Add("City1");
// Add a City to State1
tvTree.Nodes[0].Nodes[1].Nodes.Add("City2");
tvTree.Nodes[0].Nodes[1].Nodes[0].Nodes.Add("Area1");
// Add an Area to City1
tvTree.EndUpdate();
btnLoad.Enabled = false;
}
 
 
How Do I Populate The TreeView Control Using An XML File
 
The TreeView control is a natural choice to display XML data, since both the XML and TreeView represent the data in a hierarchical format. The TreeView control has a Nodes collection with root TreeNode objects. Each TreeNode in turn has its own Nodes collection that holds more than one child TreeNode.
 
The following example demonstrates how to populate a TreeView control by using XML data. Add a reference to System.XML in the using directive and a button (btnLoadXml) on to the form. The example starts by creating a DOM Document and loading the XML data into it. After initializing the TreeView control, populate the TreeView with the DOM nodes. In the AddNode() method, loop through the XML nodes until the leaf is reached. Add the nodes to the TreeView during the looping process.
 
 
private void btnLoadXml_Click(object sender, EventArgs e)
{
try
{
// Create a DOM Document and load the XML data into it.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\Documents and Settings\sagarwal\My Documents\Visual Studio 2005\Projects\Controls\Controls\Resources\anyvalidxml.xml");
 
// Initialize the TreeView control.
tvTree.Nodes.Clear();
tvTree.Nodes.Add(new TreeNode(xmlDoc.DocumentElement.Name));
TreeNode tNode = new TreeNode();
tNode = tvTree.Nodes[0];
 
// Populate the TreeView with the DOM nodes.
AddNode(xmlDoc.DocumentElement, tNode);
tvTree.ExpandAll();
}
catch (XmlException xmlEx)
{
MessageBox.Show(xmlEx.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
 
}
 
private void AddNode(XmlNode xmlNode, TreeNode treeNode)
{
XmlNode xNode;
TreeNode tNode;
XmlNodeList xNodeList;
int i;
 
// Loop through the XML nodes until the leaf is reached.
// Add the nodes to the TreeView during the looping process.
if (xmlNode.HasChildNodes)
{
xNodeList = xmlNode.ChildNodes;
for (i = 0; i <= xNodeList.Count - 1; i++)
{
xNode = xmlNode.ChildNodes[i];
treeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = treeNode.Nodes[i];
AddNode(xNode, tNode);
}
}
else
{
// Here you need to pull the data from the XmlNode based on the
// type of node, whether attribute values are required, and so forth.
treeNode.Text = (xmlNode.OuterXml).Trim();
}
}
 
 
How Do I Drag And Drop Nodes In A TreeView Control
 
Microsoft has added a series of properties and events to help you use drag and drop with your controls.  You must set the property AllowDrop = True to allow for dragging and dropping within the tree view. 
 
In the code example demonstrated below, The TreeView control provides three events that you must handle:
 
  • MouseDown – Occurs when the mouse pointer is over the control and a mouse button is pressed. If there is a node at the mouse pointer, Clone a copy of the node and do drag-and-drop operation.
  • DragOverOccurs when an object is dragged over the control's bounds.This event provides mouse coordinates in the screen. You need to convert this point to a point in the TreeView control's coordinate system.
  • DragDrop - Occurs when a drag-and-drop operation is completed. The X and Y properties of the DragEventArgs are in screen coordinates, not client coordinates. We convert the properties to a client Point using pt = tv.PointToClient(pt).
 
Add the following events to the CreateTreeViewControl() method
 
tvTree.DragDrop += new DragEventHandler(tvTree_DragDrop);
tvTree.MouseDown +=new MouseEventHandler(tvTree_MouseDown);
tvTree.DragOver += new DragEventHandler(tvTree_DragOver);
 
private void tvTree_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
// Get the tree.
TreeView tv = (TreeView)sender;
 
// Get the node
TreeNode tNode = tv.GetNodeAt(e.X, e.Y);
tv.SelectedNode = tNode;
 
// Clone a copy of the node and do drag-and-drop operation
if (tNode != null)
{
tv.DoDragDrop(tNode.Clone(), DragDropEffects.Copy);
}
}
 
 
private void tvTree_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
{
// Get the tree.
TreeView tv = (TreeView)sender;
 
e.Effect = DragDropEffects.None;
 
// If valid
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 = tv.PointToClient(pt);
 
// Drop the nodes over a valid node
TreeNode tNode = tv.GetNodeAt(pt);
if (tNode != null)
{
e.Effect = DragDropEffects.Copy;
tv.SelectedNode = tNode;
}
}
}
 
 
 
private void tvTree_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
 
// Get the tree.
TreeView tv = (TreeView)sender;
 
// Get the screen point.
Point pt = new Point(e.X, e.Y);
 
pt = tv.PointToClient(pt);
 
// Get the node at the mouse pointer
TreeNode tNode = tv.GetNodeAt(pt);
 
// Add a child node.
tNode.Nodes.Add((TreeNode)e.Data.GetData(typeof(TreeNode)));
 
tNode.Expand();
 
 
}
 
Conclusion :
 
In this article, we saw a recipe approach to performing some of the most common tasks with the TreeView Control. I hope the article was useful and I thank you for viewing it.
 
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by dinesh on Tuesday, October 16, 2007 8:10 AM
i want to drag a item from treeView1 and to drop that in treeView2 then that item should added in treeView2 and should deleted in treeView1
Comment posted by Suprotim Agarwal on Saturday, October 20, 2007 6:14 AM
Dear Dinesh,
Check this example over here
http://www.codeproject.com/vb/net/DragDropPersistingTreeV.asp
Comment posted by Manigandan on Thursday, December 20, 2007 11:49 AM
I need these functionality with web form. i think ..,Here specified only window form with drag and drop function in tree view.
Comment posted by Suprotim Agarwal on Friday, December 21, 2007 11:49 PM
Hello, For Drag and Drop in Treeview using asp.net, check out this site : http://www.obout.com/grid/grid_and_tree.aspx
Comment posted by waseem on Thursday, June 5, 2008 5:11 AM
Can you tell me this, how can i add same data in Vb.NET win Forms?