Jose M.
Jose M.

Reputation: 2340

image drag and drop - how to get image

I am trying to write a program that allows the user to drag and drop an image from any folder to the form's picture box. I got the drag and drop part, but I don't know to do is how to store the image on a variable to be able to be dropped on the picturebox. Here is what I have so far:

    Public Sub New()


    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

    AddHandler picCategoryImage.DragDrop, AddressOf picCategoryImage_DragDrop
    AddHandler picCategoryImage.DragEnter, AddressOf picCategoryImage_DragEnter

End Sub

Private Sub picCategoryImage_DragDrop(sender As Object, e As DragEventArgs) Handles picCategoryImage.DragDrop

    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

Private Sub picCategoryImage_DragEnter(sender As Object, e As DragEventArgs) Handles picCategoryImage.DragEnter

    If e.Data.GetDataPresent(DataFormats.Bitmap) Then

        e.Effect = DragDropEffects.Copy

    Else

        e.Effect = DragDropEffects.None

    End If


End Sub

where am I going wrong here?

Upvotes: 0

Views: 3221

Answers (1)

You need DataFormats.FileDrop instead of DataFormats.Bitmap in DragEnter event. And in DragDrop you open the file name you get from e.Data.GetData():

Private Sub picCategoryImage_DragDrop(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles picCategoryImage.DragDrop
    Dim picbox As PictureBox = CType(sender, PictureBox)

    Dim files() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())

    If files.Length <> 0 Then
        Try
            picbox.Image = Image.FromFile(files(0))
        Catch ex As Exception
            MessageBox.Show("Problem opening file ")
        End Try
    End If
End Sub

Private Sub picCategoryImage_DragEnter(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles picCategoryImage.DragEnter
    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        e.Effect = DragDropEffects.Copy
    Else
        e.Effect = DragDropEffects.None
    End If
End Sub

You need also to set(in form load event):

picCategoryImage.AllowDrop = True

Upvotes: 3

Related Questions