In a Windows application, drag and drop is a common operation performed by users for moving or copying data from one control to another control. In most of the cases, this data may be simple text, file, image, a music file, or it can even be an OLE object. Fortunately, Microsoft .NET technology has given many events and methods by which a programmer can implement drag and drop operation in their applications.
Here I am explaining how to perform drag and drop operation for images. The user can drag an image from one control and drop that image on another control. The control can be a
PictureBox or it can be a
Panel. I have given a simple application which demonstrates how to drag an image from one panel and drop that image into another panel by using the
MouseDown events and the
DragAllow property. You require at least these three events and the property for implementing drag and drop support. Following is the explanation of these three events and the property.
This property is set to
true for any control for which we want drag and drop support. This control may be a
ListBox, or a
Panel which holds data.
This event is fired whenever the mouse with a pressed left button will enter into a control’s region. At that time, the control’s
DragEnter event is fired. Generally, we require to check the type of data available, which is done as follows.
private void panel_DragEnter(object sender, DragEventArgs e)
e.Effect = DragDropEffects.Copy;
e.Effect = DragDropEffects.None;
Whenever the mouse is pressed on any control, that control’s mouse down event is fired. Generally, in this event, data that we want to drag is given as follows:
private void panel_MouseDown(object sender, MouseEventArgs e)
Panel source = (Panel)sender;
This event is fired when the left mouse button is released by the user and the user intends to drop data on the target control. Generally, the target control accepts data here as follows.
private void panel_DragDrop(object sender, DragEventArgs e)
Panel destination = (Panel)sender;
destination.BackgroundImage = (Bitmap)e.Data.GetData(typeof(Bitmap));
All the code above is related to
Bitmap data only. If you want drag and drop for text data, use the