This blog will show you how you can perform drag and drop operations on treeview control node using C#.Net in Windows application. So for this article first we will create a new windows application and add the below code on form load.
- private void Form2_Load(object sender, EventArgs e)
- {
- treeView1 = new TreeView();
-
- this.SuspendLayout();
-
-
- treeView1.AllowDrop = true;
- treeView1.Dock = DockStyle.Fill;
-
-
- TreeNode node;
- for (int x = 0; x < 5; ++x)
- {
-
- node = treeView1.Nodes.Add(String.Format("Node{0}", x * 4));
- for (int y = 1; y < 6; ++y)
- {
-
- node = node.Nodes.Add(String.Format("Node{0}", x * 4 + y));
- }
- }
-
-
- treeView1.ItemDrag += new ItemDragEventHandler(treeView1_ItemDrag);
- treeView1.DragEnter += new DragEventHandler(treeView1_DragEnter);
- treeView1.DragOver += new DragEventHandler(treeView1_DragOver);
- treeView1.DragDrop += new DragEventHandler(treeView1_DragDrop);
-
-
- this.ClientSize = new Size(292, 273);
- this.Controls.Add(treeView1);
-
- this.ResumeLayout(false);
- }
In the above code I have created nodes of tree view. Now we will perform the operation for the drag and drop feature. First create the tree view control treeView1_ItemDrag event and add the below code.
- private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
- {
-
- if (e.Button == MouseButtons.Left)
- {
- DoDragDrop(e.Item, DragDropEffects.Move);
- }
-
-
- else if (e.Button == MouseButtons.Right)
- {
- DoDragDrop(e.Item, DragDropEffects.Copy);
- }
- }
After this we will create the treeView1_DragEnter event.
- private void treeView1_DragEnter(object sender, DragEventArgs e)
- {
- e.Effect = e.AllowedEffect;
- }
Now we will create the treeView1_DragOver event,
- private void treeView1_DragOver(object sender, DragEventArgs e)
- {
-
- Point targetPoint = treeView1.PointToClient(new Point(e.X, e.Y));
-
-
- treeView1.SelectedNode = treeView1.GetNodeAt(targetPoint);
- }
Now we will create the treeView1_DragDrop event,
- private void treeView1_DragDrop(object sender, DragEventArgs e)
- {
-
- Point targetPoint = treeView1.PointToClient(new Point(e.X, e.Y));
-
-
- TreeNode targetNode = treeView1.GetNodeAt(targetPoint);
-
-
- TreeNode draggedNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
-
-
-
- if (!draggedNode.Equals(targetNode) && !ContainsNode(draggedNode, targetNode))
- {
-
-
- if (e.Effect == DragDropEffects.Move)
- {
- draggedNode.Remove();
- targetNode.Nodes.Add(draggedNode);
- }
-
-
-
- else if (e.Effect == DragDropEffects.Copy)
- {
- targetNode.Nodes.Add((TreeNode)draggedNode.Clone());
- }
-
-
-
- targetNode.Expand();
- }
-
- }
After that we will use the below function to perform parent child relation,
- private bool ContainsNode(TreeNode node1, TreeNode node2)
- {
-
- if (node2.Parent == null) return false;
- if (node2.Parent.Equals(node1)) return true;
-
-
-
-
- return ContainsNode(node1, node2.Parent);
- }
Now we are done. Run the code to check the output.