Windows Forms: How to Drag and Drop an Image from one PictureBox into another in C#

This post shows you Drag and Drop an Image from one PictureBox into another in C# .NET Windows Forms Application.

Drag and drop images is extremely useful feature, you can easily program drag and drop images in c# winform.

Creating a new Windows Forms Application project, then open your form designer. Next, Drag two PictureBox controls from the visual studio toolbox to your winform.

c# drag drop image

Adding a Form_Load event handler to your form allows you to set the AllowDrop property of PictureBox control to true.

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

Adding a DragDrop event handler to the PictureBox 1 allows you to drag an image from your hard disk to your PictureBox control.

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]);
    }
}

Adding a DragEnter event handler to the PictureBox 1 allows you to set the Effect property to the PictureBox control.

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

Adding a MouseDown event handler to the PictureBox 1 allows you to copy an image to the PictureBox control.

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

Adding a DragEnter event handler to the PictureBox 2 allows you to set Effect property to the PictureBox control.

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;
}

Adding a DragDrop event handler to the PictureBox 2 allows you to copy an image from the PictureBox 1.

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

Through the c# example, you have learned how to drag and drop image from hard disk to the PictureBox control and Drag images between PictureBox controls.

VIDEO TUTORIAL