Live Chat Icon For mobile
Live Chat Icon

How do I make the TreeView scroll when I drag an item to the top or bottom?

Platform: WinForms| Category: TreeView

When you drag an item within the TreeView, you can handle the DragOver event for a drag-drop. If you want to drag-drop into a spot that’s not currently visible, you can scroll the TreeView by handling the DragOver event:

[C#]	
	private void treeView1_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
	{
		TreeView tv = sender as TreeView;
		Point pt = tv.PointToClient(new Point(e.X,e.Y));
			
		int delta = tv.Height - pt.Y;
		if ((delta < tv.Height / 2) && (delta > 0))
		{
			TreeNode tn = tv.GetNodeAt(pt.X, pt.Y);
			if (tn.NextVisibleNode != null)
				tn.NextVisibleNode.EnsureVisible();
		}
		if ((delta > tv.Height / 2) && (delta < tv.Height))
		{
			TreeNode tn = tv.GetNodeAt(pt.X, pt.Y);
			if (tn.PrevVisibleNode != null)
				tn.PrevVisibleNode.EnsureVisible();
		}
	} 

[VB.NET]
Private Sub treeView1_DragOver(sender As Object, e As System.Windows.Forms.DragEventArgs)
   
  If TypeOf sender is TreeView  Then
  	Dim tv As TreeView = CType(sender, TreeView)    
  	Dim pt As Point = tv.PointToClient(New Point(e.X, e.Y))
  	Dim delta As Integer = tv.Height - pt.Y
  	If delta < tv.Height / 2 And delta > 0 Then
      		Dim tn As TreeNode = tv.GetNodeAt(pt.X, pt.Y)
      		If Not (tn.NextVisibleNode Is Nothing) Then
         		tn.NextVisibleNode.EnsureVisible()
      		End If 
   	End If 
   	If delta > tv.Height / 2 And delta < tv.Height Then
      		Dim tn As TreeNode = tv.GetNodeAt(pt.X, pt.Y)
      		If Not (tn.PrevVisibleNode Is Nothing) Then
           		tn.PrevVisibleNode.EnsureVisible()
      		End If 
   	End If 
  End If
End Sub ’treeView1_DragOver 

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.