Drag and Drop in Visual Basic
March 18th, 2007Drag and drop refers to a functionality that allows a user to select one or several objects, drag over a "target" in the user interface and drop them. Such functionality is very common in many windows applications. For example, in Windows Explorer, you can drag and drop files to folders as a way to copy or move them around. Or, if you drag a text file from Windows Explorer on to a Notepad window, Notepad opens the file.

Implementing drag and drop functionality in Visual Basic is easy. It involves handling events that are related to drag and drop operations. The process starts when an item is dragged from a source control and dragged over to a target control that can accept the drop. The drag and drop operation terminates when the user releases the mouse button to indicate a drop. Below is a code snippet that shows how the TreeView1 control handles the DragDrop event. As you will see, it checks if it can find a ListViewItem in the object that is dropped. If there is, then the item is added to the treeview at the node where the mouse cursor was at.
Dim nNode As ListViewItem
If e.Data.GetDataPresent("System.Windows.Forms.ListViewItem", False) Then
Dim pt As Point
Dim targetNode As TreeNode
pt = CType(sender, TreeView).PointToClient(New Point(e.X, e.Y))
targetNode = CType(sender, TreeView).GetNodeAt(pt)
nNode = CType(e.Data.GetData("System.Windows.Forms.ListViewItem"), ListViewItem)
If IsNothing(targetNode) Then
TreeView1.Nodes.Add(nNode.Text)
Else
targetNode.Nodes.Add(nNode.Text)
targetNode.Expand()
End If
End If
End Sub
Download the sample project here .
Posted in Visual Basic | No CommentsNo Comments yet »
RSS feed for comments on this post. TrackBack URI
Leave a comment
(C) by Virgilio Adriano. All rights reserved. Powered by WordPress.
Entries and comments feeds.
It took 0.297 seconds to load this page.