Drag and Drop Image on PictureBox in Winfoms Form

In this blog we learn how to drag drop image file on picturebox in Winforms.
 
Step 1: Create new windows application in C#.
 
Step 2: Take picturebox control and place it on form as below.
 
 
 
Step 3:  Set AllowDrop property of form as True.
 
Step 4: Write following code.

using System;

using System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms;
using
System.IO;
using
System.Threading;
using
System.Diagnostics;

namespace WindowsFormsApplication1

{
   
public partial class Form1 : Form
    {

        protected bool validData;

        string path;
       
protected Image image;
       
protected Thread getImageThread
        public Form1()
        {

            InitializeComponent();

        }

        private void Form1_DragEnter(object sender, DragEventArgs e)

        {
           
string filename;
            validData = GetFilename(
out filename, e);
           
if (validData)
            {

                path = filename;

                getImageThread =
new Thread(new ThreadStart(LoadImage));
                getImageThread.Start();

                e.Effect = DragDropEffects.Copy;

            }

           
else
                e.Effect = DragDropEffects.None;

        }

       
private bool GetFilename(out string filename, DragEventArgs e)
        {
           
bool ret = false;
            filename =
String.Empty;
           
if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
            {
               
Array data = ((IDataObject)e.Data).GetData("FileDrop") as Array;
               
if (data != null)
                {

                   
if ((data.Length == 1) && (data.GetValue(0) is String))
                    {

                        filename = ((
string[])data)[0];
                       
string ext = Path.GetExtension(filename).ToLower();
                       
if ((ext == ".jpg") || (ext == ".png") || (ext == ".bmp"))
                       {

                            ret =
true;
                        }

                    }

                }

            }

           
return ret;
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)

        {
           
if (validData)
            {

               
while (getImageThread.IsAlive)
                {

                    Application.DoEvents();

                   
Thread.Sleep(0);
                }

                pictureBox1.Image = image;

            }

        }

        protected void LoadImage()

        {
            image =
new Bitmap(path);
        }

    }

}

Step 5: Run application.
 
Step 6: Drag drop image file on form.
 
 
 
Step 7: The image in picturebox will change as below.
 
 
Ebook Download
View all
Learn
View all