Drag and Drop Images Into a PictureBox

Posted by: Suprotim Agarwal , on 7/25/2008, in Category WinForms & WinRT
Views: 94294
Abstract: This article was written simply out of curiosity. I was doing a similar operation using web technologies and just wanted to try out how it works with Windows Forms. I have recorded the steps in this short article, where we will explore how to drag and drop images into a PictureBox.
Drag and Drop Images Into a PictureBox
 
This article was written simply out of curiosity. I was doing a similar operation using web technologies and just wanted to try out how it works with Windows Forms. I have recorded the steps in this short article, where we will explore how to drag and drop images into a PictureBox.
Step 1: Open Visual Studio > File > New > Project. In the Project Types pane, choose the language of your choice (Visual C# or Visual Basic). In the Templates pane, choose Windows Application. Choose a name and location for the project and click OK.
Step 2: Now Drag and drop a Button(btnImage) control and a PictureBox(picBox) control to the form.  We will first add an image to the Button and then at runtime, drag and drop that image from the Button to the PictureBox. You can try out the same with other controls as well that support the image property.
Now if we need to verbally describe how the entire drag drop process is going to occur, then here it is. The user will move the mouse pointer over the button, press it and then instead of just releasing the mouse, the user will drag the image over to the PictureBox. The following events need to be handled.
Button MouseDown Event – which will be handled when the mouse pointer is over the Button and a mouse button is pressed.
PictureBox DragEnter Event – this event will be handled when the Picture is dragged into the PictureBox’s bounds.
PictureBox DragDrop Event - Occurs when a drag-and-drop operation is completed.
Step 3: With these inputs, let us move ahead and add some code to our form. In the Form1.cs or Form1.vb, add the following code in the constructor of the Form
C#
        public Form1()
        {
            InitializeComponent();
 
            Image img = Image.FromFile(@"C:\pics\1.jpg");
            this.btnImage.Image = img;
            this.picBox.AllowDrop = true;
            this.btnImage.MouseDown += new System.Windows.Forms.MouseEventHandler(this. btnImage_MouseDown);
            this.picBox.DragDrop += new System.Windows.Forms.DragEventHandler(this.pictureBox_DragDrop);
            this.picBox.DragEnter += new System.Windows.Forms.DragEventHandler(this.pictureBox_DragEnter);
        }
VB.NET
            Public Sub New()
                  InitializeComponent()
 
                  Dim img As Image = Image.FromFile("C:\pics\1.jpg")
                  Me.btnImage.Image = img
                  Me.picBox.AllowDrop = True
                  AddHandler btnImage.MouseDown, AddressOf btnImage _MouseDown
                  AddHandler picBox.DragDrop, AddressOf pictureBox_DragDrop
                  AddHandler picBox.DragEnter, AddressOf pictureBox_DragEnter
            End Sub
In the code above, we added an image to the Button and also registered the events for the PictureBox and Button.
Step 4: Moving ahead, we will now add code to the respective events discussed above:
C#
        private void btnImage_MouseDown(object sender, MouseEventArgs e)
        {
            Button btnPic = (Button)sender;
            btnPic.DoDragDrop(btnPic.Image, DragDropEffects.Copy);
        }
 
        private void pictureBox_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Bitmap))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
 
        private void pictureBox_DragDrop(object sender, DragEventArgs e)
        {
            PictureBox picbox = (PictureBox)sender;
            Graphics g = picbox.CreateGraphics();
            g.DrawImage((Image)e.Data.GetData(DataFormats.Bitmap), new Point(0, 0));
        }
VB.NET
            Private Sub btnImage_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
                  Dim btnPic As Button = CType(sender, Button)
                  btnPic.DoDragDrop(btnPic.Image, DragDropEffects.Copy)
            End Sub
 
            Private Sub pictureBox_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs)
                  If e.Data.GetDataPresent(DataFormats.Bitmap) Then
                        e.Effect = DragDropEffects.Copy
                  Else
                        e.Effect = DragDropEffects.None
                  End If
            End Sub
 
            Private Sub pictureBox_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs)
                  Dim picbox As PictureBox = CType(sender, PictureBox)
                  Dim g As Graphics = picbox.CreateGraphics()
                  g.DrawImage(CType(e.Data.GetData(DataFormats.Bitmap), Image), New Point(0, 0))
            End Sub
In the btnImage_MouseDown event, we call the DoDragDrop method on the sender. This method begins a drag and drop operation and accepts a parameter of the object that is being dragged and the effect of a drag drop, as the second parameter.
In the pictureBox_DragEnter we check whether the specified data type(Bitmap) exists in the object. This method is called before GetData().
Finally in the pictureBox_DragDrop we call the DrawImage() which accepts the specified image and the specified location and draws the portion of the image on the PictureBox.
That’s it. Run the sample and you will be able to perform drag drop operations on the PictureBox. I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed. 
 
Give me a +1 if you think it was a good article. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Suresh on Tuesday, July 29, 2008 11:19 PM
The following code doesnt seem to work.
-------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Form_Drag_IMG_PictureBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Image img = Image.FromFile(@"c:\temp\go_search_button.gif");
            this.button1.Image = img;
            this.pictureBox1.AllowDrop = true;
            this.button1.MouseDown +=new MouseEventHandler(button1_MouseDown);
            this.pictureBox1.DragEnter += new DragEventHandler(pictureBox1_DragEnter);
            this.pictureBox1.DragDrop += new DragEventHandler(pictureBox1_DragDrop);            
        }

        void pictureBox1_DragDrop(object sender, DragEventArgs e)
        {
            PictureBox picBox = (PictureBox)sender;
            Graphics g = picBox.CreateGraphics();
            g.DrawImage((Image)e.Data.GetData(DataFormats.Bitmap), new Point(0,0));
            //throw new Exception("The method or operation is not implemented.");
        }

        void pictureBox1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Bitmap))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
            //throw new Exception("The method or operation is not implemented.");
        }

        private void button1_MouseDown(object sender, MouseEventArgs e)
        {
            Button btnPic = (Button)sender;
            btnPic.DoDragDrop(btnPic, DragDropEffects.Copy);
        }

        
    }
}
Comment posted by harihar on Wednesday, September 3, 2008 7:06 AM
very atractive
Comment posted by James on Friday, September 12, 2008 10:59 AM
This was very helpful. Thanks!
Comment posted by Nithya K on Wednesday, October 8, 2008 7:57 AM
Good coding,i have done,thank u very much
Comment posted by Alex on Tuesday, January 13, 2009 3:42 PM
g.DrawImage((Image)e.Data.GetData(DataFormats.Bitmap), new Point(0, 0));

It will not work :).

1. e.Data.GetData(DataFormats.Bitmap) - Memory stream. So should be:
   g.DrawImage(Image.FromStream((MemoryStream)e.Data.GetData(DataFormats.Bitmap)), new Point(0, 0));

2. Why did you use Graphics and DrawImage, why don't
   picbox.Image = ...?

        private void pictureBox_DragDrop(object sender, DragEventArgs e)
        {
            PictureBox picbox = (PictureBox)sender;
            Graphics g = picbox.CreateGraphics();
            g.DrawImage((Image)e.Data.GetData(DataFormats.Bitmap), new Point(0, 0));
        }

can be:

        private void pictureBox_DragDrop(object sender, DragEventArgs e)
        {
            PictureBox picbox = (PictureBox)sender;
            picbox.Image = Image.FromStream((MemoryStream)e.Data.GetData(DataFormats.Bitmap);
            picbox.Refresh();
        }

But if you use Graphics you should dispose it or use using(Graphics g = picbox.CreateGraphics()){}
Comment posted by Alex on Tuesday, January 13, 2009 5:13 PM
g.DrawImage((Image)e.Data.GetData(DataFormats.Bitmap), new Point(0, 0));

It will not work :).

1. e.Data.GetData(DataFormats.Bitmap) - Memory stream. So should be:
   g.DrawImage(Image.FromStream((MemoryStream)e.Data.GetData(DataFormats.Bitmap)), new Point(0, 0));

2. Why did you use Graphics and DrawImage, why don't
   picbox.Image = ...?

        private void pictureBox_DragDrop(object sender, DragEventArgs e)
        {
            PictureBox picbox = (PictureBox)sender;
            Graphics g = picbox.CreateGraphics();
            g.DrawImage((Image)e.Data.GetData(DataFormats.Bitmap), new Point(0, 0));
        }

can be:

        private void pictureBox_DragDrop(object sender, DragEventArgs e)
        {
            PictureBox picbox = (PictureBox)sender;
            picbox.Image = Image.FromStream((MemoryStream)e.Data.GetData(DataFormats.Bitmap);
            picbox.Refresh();
        }

But if you use Graphics you should dispose it or use using(Graphics g = picbox.CreateGraphics()){}
Comment posted by duguma on Friday, May 29, 2009 2:53 PM
the code is very good and clear it helps the programmer.But it is more clear if the graphical window forms included.
Thanks
Comment posted by ParkashKaur on Monday, March 15, 2010 5:30 AM
This is very helpful for me. Thanks to create such help.
Comment posted by Johnny on Sunday, June 13, 2010 5:48 PM
Very nice! Helped me out a lot. Thanks !
Comment posted by halil güneş on Thursday, July 22, 2010 7:36 AM
PictureBox control have not AllowDrop property. But There is this property in your article.
Comment posted by Joey Zhao on Thursday, December 9, 2010 8:06 PM
but I can't find 'AllowDrop' property of PictureBox in vs2010 (framework4.0).is there any other way to do this?thanks
Comment posted by Joey Zhao on Thursday, December 9, 2010 8:27 PM
I think I can put the PictueBox into a Panel ,because a Panel contains the AllowDrop property.but why PictureBox do not contains AllowDrop property in framework 4
Comment posted by jo0ls on Saturday, January 8, 2011 5:27 AM
AllowDrop is marked as "For internal use only" in the msdn. If you run as administrator then you don't get any "drag enter" windows messages posted to the control, so drag enter never fires. Not sure about the rest of the drag and drop messages, but it does seem to be broken.
Comment posted by Nitesh on Friday, March 11, 2011 12:07 AM
the code for drag and drop is ok but images are all dropped in the same position.
Comment posted by hendra on Friday, November 18, 2011 5:11 AM
thank you for the tutorial...:)
Comment posted by hendra on Saturday, November 26, 2011 1:26 AM
how to save it to access??
Comment posted by anusha on Monday, January 2, 2012 10:17 AM
i need d codes for drag and dropping d pictures from a command button to a picturebox.. help me out..
Comment posted by Kyosumaru on Saturday, January 21, 2012 8:05 PM
A first chance exception of type 'System.IO.FileNotFoundException' occurred in System.Drawing.dll

this pop up when i run the form... what should i do???
Comment posted by Kirupa on Tuesday, January 24, 2012 7:05 AM
This article was very helpful.
Thank You.
What is my requirement is
On Mouse Over the image has to move based on the X,Y Co-ordinates in Windows Application.
Can U help me..
Comment posted by Cedu on Monday, December 3, 2012 7:29 AM
C#
Why not only "picBox.Image = (Image)(e.Data.GetData(DataFormats.Bitmap));" ?
Comment posted by Babulal on Thursday, January 10, 2013 7:11 AM
Simply very very thanks
Comment posted by Dat on Wednesday, January 23, 2013 10:51 PM
Thank you very much.
Now, I want to drag an image from window explore to my picture box. How my picture box display the image. Can everyone help me?

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel