You mention this is a "User Control". In this case I use two different approaches in which I can reference my dynamically added user controls after they have been added to a form or another control.
In the first scenario I designed a user control which I can add more than one of them at the same time.
Here I declare them:
Public Shared imgViewer1 As New _ucImageViewer
Public imgViewer2 As New _ucImageViewer
Public imgViewer3 As New _ucImageViewer
Public imgViewer4 As New _ucImageViewer
(multiple instances of the same user controls)
.. and here I add them to the form or control
With imgViewer2
.Tag = "2"
.lblNumberTag.Text = "2"
.cbSyncViewers.Enabled = True
.tabImageControls.Visible = False
.Location = New Point(imgViewer1.Location.X + imgViewer1.Width, imgViewer1.Location.Y)
.Width = imgViewer1.Width
.Height = imgViewer1.Height
.tsMagnifier.Enabled = False
.tsSnapshot.Enabled = False
End With
pnlMainDisplayArea.Controls.Add(imgViewer2)
Alright, this is in a controlled environment where I know exactly how many user controls I will be adding. What if I don't know how many I will be needing ?
In this scenario, I use the TAG property extensively. When I create a control dynamically, I insert unique information into the Tag property in order for me to address that specific control when I need to.
Here I add the control to the form or another control:
Dim picbox As PictureBox
In my Sub or Function I do the following when adding the control dynamically:
Dim picbox As New PictureBox
picbox.Image = Image.FromStream(msThumb)
If Left > pnlConsultationImages.Width - 138 Then
Left = 12
Top = Top + 134
End If
With picbox
.Size = New Size(128, 128)
.SizeMode = PictureBoxSizeMode.Zoom
.Top = Top
.Left = Left
.Visible = True
.Tag = dbConID & "#" & clReadFromDB.tmbData.Rows(i).Item(1).ToString
End With
pnlConsultationImages.Controls.Add(picbox)
AddHandler picbox.Click, New System.EventHandler(AddressOf PreviewImage)
AddHandler picbox.DoubleClick, New System.EventHandler(AddressOf AddtoSelection)
AddHandler picbox.MouseEnter, New System.EventHandler(AddressOf pnlImages_MouseEnter)
AddHandler picbox.MouseLeave, New System.EventHandler(AddressOf pnlImages_MouseLeave)
Schweet... now I have a dynamically added control somewhere on my form but how to I address it ?
For Each img As Control In pnlSelectedImages.Controls
If TypeOf img Is PictureBox Then
If img.Tag Is sender.Tag Then
Return
End If
End If
Next