Search code examples
vb.netpicturebox

Assign an image to a picturebox from another form


I have a program with 16 blank picturebox's on the main form (MainForm).

When a user clicks a box a second form (form2) is opened which has 17 pictureboxes, each with a specific image. I want the specific image to go into the picturebox that was clicked on the main form.

I used this code on form2 when one of the 17 pictureboxes is clicked

With Mainform.picturebox1
    .image = My.Resources._apicture01
     End With

However, when I click on picturebox2 on the main form the picture chosen in form2 is assigned to Mainform.picturebox1 rather than picturebox2.

I need a way of having the code figure out which of the 16 pictureboxes on the main form was clicked, then have it add the chosen image to that picturebox.


Solution

  • I think there a two ways. The first assumes that your form2 is used to select the photo only and then closes, returning to the Main form.

    In this case, add a public image property to form2 like this:

    Private _selectedImage As Image
    Public ReadOnly Property SelectedImage As Image
        Get
            Return _selectedImage
        End Get
    End Property
    

    then in form2, when selecting the image, set _selectedImage to the image and close the form with:

    Me.DialogResult = DialogResult.OK
    

    Back in Main form, set an event handler for Click event of all picture boxes like:

    AddHandler PictureBox1.Click, AddressOf PictureBox_Click
    AddHandler PictureBox2.Click, AddressOf PictureBox_Click
    

    and so on. The click event handler should be something like this:

        Private Sub PictureBox_Click(sender As Object, e As EventArgs) 
          Dim PB As PictureBox = DirectCast(sender, PictureBox)
          Using F As New Form2()
            If F.ShowDialog = DialogResult.OK Then
                PB.Image = F.SelectedImage
            End If
          End Using
        End Sub
    

    The other way would be to pass the picturebox to Form2 either as a property or as a parameter and then setting image to that picturebox in Form2, but I prefer option 1.