Windows Forms: Drag and drop image from one PictureBox to another PictureBox in C#

This post shows you how to drag and drop an image from one PictureBox to another PictureBox in C# Windows Forms Application.

To create a simple demo how to use c# drag and drop image to picturebox, you need to drag the PictureBox control from the visual studio toolbox to your winform, then layout your UI to help you drag and drop image to picturebox in c# as shown below.drag image in picturebox c#

Add the load event handler to your form allows you to initialize PictureBox controls.

private void Form1_Load(object sender, EventArgs e)
{
    pictureBox1.AllowDrop = true;
    pictureBox2.AllowDrop = true;
}

Add the DragDrop event handler to the PictureBox1 allows you to drag drop an image file to the PictureBox control as the following c# code.

private void pictureBox1_DragDrop(object sender, DragEventArgs e)
{
    var data = e.Data.GetData(DataFormats.FileDrop);
    if (data != null)
    {
        var fileNames = data as string[];
        if (fileNames.Length > 0)
            pictureBox1.Image = Image.FromFile(fileNames[0]);
    }
}

And don't forget to add the DragEnter event handler to the PictureBox1 allows you to copy an image.

private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.Copy;
}

Finally, Add the MouseDown event handler to the PictureBox1 to perform image copying.

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
        pictureBox1.DoDragDrop(pictureBox1.Image, DragDropEffects.Copy);
}

Next, Add the DragEnter to the PictureBox2 allows you to copy an image.

private void pictureBox2_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.Bitmap) && (e.AllowedEffect & DragDropEffects.Copy) != 0)
        e.Effect = DragDropEffects.Copy;
    else
        e.Effect = DragDropEffects.None;
}

Finally, Add the DragDrop event handler to the PictureBox2 to allows you to copy an image from clipboard as the following c# code.

private void pictureBox2_DragDrop(object sender, DragEventArgs e)
{
    pictureBox2.Image = (Bitmap)e.Data.GetData(DataFormats.Bitmap, true);
}

Press F5 to run your project, then drag and drop image to PictureBox1. Next, you can drag and drop the image from PictureBox1 to PictureBox2.

VIDEO TUTORIAL