SoFunction
Updated on 2025-03-01

C# method to implement TreeView node dragging

This article describes the method of implementing TreeView node dragging and dropping in C#. Share it for your reference. The details are as follows:

public Form1()
{
 InitializeComponent();
  = true;
  += new ItemDragEventHandler(treeView1_ItemDrag);
  += new DragEventHandler(treeView1_DragEnter);
  += new DragEventHandler(treeView1_DragDrop);
}
void treeView1_DragDrop(object sender, DragEventArgs e)
{
 TreeNode moveNode = (TreeNode)("");
 //Determine the target node to be moved according to the mouse coordinates Point pt;
 TreeNode targeNode;
 pt = ((TreeView)(sender)).PointToClient(new Point(, ));
 targeNode = this.(pt);
 //If the target node has no child nodes, it will be added as a node of the same level, otherwise it will be added to the late end of the lower level node. TreeNode NewMoveNode = (TreeNode)();
 if ( == 0)
 {
  (, NewMoveNode);
 }
 else
 {
  (, NewMoveNode);
 }
 //Update the currently dragged node selection  = NewMoveNode;
 //Expand the target node to facilitate the display of drag and drop effect ();
 //Remove drag and drop node ();
}
void treeView1_DragEnter(object sender, DragEventArgs e)
{
 if ((""))
 {
   = ;
 }
 else
 {
   = ;
 }
}
void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
{
 if ( == )
 {
  DoDragDrop(, );
 }
}

I hope this article will be helpful to everyone's C# programming.