How do I get a value from a dynamic control?

55 views Asked by At

I've got a form with a picturecontrol (default to black bg) and I have a flowlayoutpanel underneath. On the form's load it cycles through a folder of images and creates a thumbnail (picturecontrol) inside the flowlayoutpanel. What I want to do is dynamically add a click event to let the user change the main picturecontrol image with one of the thumbnails.

Private Sub TabImageLoad()
    Dim apppath As String = Application.StartupPath()
    Dim strFileSize As String = ""
    Dim di As New IO.DirectoryInfo(apppath + "\images")
    Dim aryFi As IO.FileInfo() = di.GetFiles("*.*")
    Dim fi As IO.FileInfo

    For Each fi In aryFi
        If fi.Extension = ".jpg" Or fi.Extension = ".jpeg" Or fi.Extension = ".gif" Or fi.Extension = ".bmp" Then
            Dim temp As New PictureBox
            temp.Image = Image.FromFile(di.ToString + "\" + fi.ToString)
            temp.Width = 100
            temp.Height = 75
            temp.Name = fi.ToString
            temp.Visible = True
            temp.SizeMode = PictureBoxSizeMode.StretchImage
            AddHandler temp.Click, AddressOf Me.temp_click
            FlowLayoutPanel1.Controls.Add(temp)
        End If
    Next
End Sub
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    PictureBox1.Image = temp.Image
End Sub

This is my code for the sub that gets the images (note the addhandler attempt) and the sub that links to the addhandler. As you've probably guessed the addhandler doesn't work because "temp" is not declared in the temp_click sub.

Any suggestions?

2

There are 2 answers

0
Tim Schmelter On BEST ANSWER

The sender argument is always the control that triggered the event, in this case a PictureBox:

Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim pb As PictureBox = DirectCast(sender, PictureBox)
    PictureBox1.Image = pb.Image
End Sub
0
TaKeR On

I suggest you to use:

Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pbDynamic as PictureBox = trycast(sender,Picturebox)

Then validate with

if pbDynamic IsNot Nothing Then
    PictureBox1.Image = pbDynamic.image
end if

This way you avoid runtime errors and null pointer exceptions