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.
-
DragOver - Occurs 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.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
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
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn