Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

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

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, 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();
  }
}

[Visual Basic]

Private Sub treeView1_DragOver(ByVal sender As Object, ByVal e As 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

Contributed from George Shepherd's Windows Forms FAQ



Page view counter