How can I drag and drop an image from one PictureBox to another?

Platform: WinForms| Category: PictureBox

The following code snippet demonstrates how you can drag and copy an image from one picturebox (Source) another (Target:


[C#]
//In the Form Load
//Set AllowDrop of the Target PictureBox to true as this property cannot be set in the Designer
this.pictureBox2.AllowDrop = true;

//Source PictureBox
private void pictureBox1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
pictureBox1.DoDragDrop( pictureBox1.Image, DragDropEffects.All );
}

//Target PictureBox
//Drag Drop Effects
private void pictureBox2_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
 {

  if ( e.Data.GetDataPresent( DataFormats.Bitmap ) )
   {
    e.Effect = DragDropEffects.Copy;
   }
  else
   e.Effect = DragDropEffects.None;
}

//Set the image to be the dragged image.
private void pictureBox2_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
if ( (e.Data.GetDataPresent(DataFormats.Bitmap)))
 {  
  this.pictureBox1.Image = (Bitmap)(e.Data.GetData(DataFormats.Bitmap));  
 }
}

[VB.NET]
’In the Form Load
’Set AllowDrop of the Target PictureBox to true as this property cannot be set in the Designer
Me.pictureBox2.AllowDrop = True
 
’Source PictureBox
Private  Sub pictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If e.Button = MouseButtons.Left Then
pictureBox1.DoDragDrop(pictureBox1.Image, DragDropEffects.All)
End If
End Sub
 
’Target PictureBox
’Drag Drop Effects
Private  Sub pictureBox2_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs)
 
  If e.Data.GetDataPresent(DataFormats.Bitmap) Then
    e.Effect = DragDropEffects.Copy
  Else 
   e.Effect = DragDropEffects.None
  End If
End Sub
 
’Set the image to be the dragged image.
Private  Sub pictureBox2_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs)
If (e.Data.GetDataPresent(DataFormats.Bitmap)) Then
  Me.pictureBox1.Image = CType((e.Data.GetData(DataFormats.Bitmap)), Bitmap)
End If
End Sub

Share with

Related FAQs

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

Please submit your question and answer.