0

I am using dynamically created controls and need to retrieve information about the control at runtime.

If IsLoaded <> "free" Then
        flow_display.Controls.Clear()
        For x As Integer = 0 To populate.Count - 1
            If populate(x).parentID = 2 Then
                Dim NewPicBox As PictureBox = New PictureBox
                NewPicBox.Size = New System.Drawing.Size(697, 50)
                NewPicBox.ImageLocation = pw_imgLink & populate(x).imageID

                AddHandler NewPicBox.Click, AddressOf catWindow
                flow_display.Controls.Add(NewPicBox)
            End If
        Next
        IsLoaded = "free"

    End If
End Sub

Here I create the control when the user clicks on the appropriate label. Right now the catWindow sub is empty. I need to figure out which button is clicked and figure out its location on the populate list. I have tried a few things and from what I've read from other questions can't seem to find anything the helps. Thanks :)

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
spkelly86
  • 97
  • 2
  • 10

1 Answers1

1

For finding out which PictureBox is pressed, your catWindow Sub should look like this:

Public Sub catWindow(ByVal sender As Object, ByVal e As EventArgs)
    Dim box As PictureBox = TryCast(sender, PictureBox)
    If box Is Nothing Then Exit Sub

    'Now "box" refers to the PictureBox that was pressed
    '...
End Sub

If you want to find it's location in the populate list, you will need to iterate through the list until you find the matching box. You could also pre-empt a property on your PictureBox that isn't doing anything else and use it to store the index. Older forms tools used to have a .Tag property especially for this kind of thing. But really, the need to do this smells like a design flaw to me.

FWIW, I'd rewrite your original sample like this:

If IsLoaded <> "free" Then

    flow_display.SuspendLayout()
    flow_display.Controls.Clear()

    For Each box As PictureBox In populate
                        .Where(Function(p) p.parentID = 2)
                        .Select(Function(p) New PictureBox() With {
                             .Size = New System.Drawing.Size(697, 50),
                             .ImageLocation pw_imgLink & p.imageID })

        AddHandler box.Click, AddressOf catWindow
        flow_display.Controls.Add(box)
    Next box

    flow_display.ResumeLayout()
    IsLoaded = "free"
End If
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • I am pulling a series of information from my database and placing it on the list. Would it be easier to accomplish this through an array or should I go about this in a completely different direction? Oh and that catWindow thing worked, THANKS! – spkelly86 Nov 08 '12 at 22:51
  • @spkelly86 look into databinding – Joel Coehoorn Nov 09 '12 at 01:21