Accessing dynamically created controls within a Windows Form?

Ok,

This question is kinda in conjunction with what I have been working on lately and along with several other questions I have posted.

I need to find how or what is the most efficient way to access dynamically created UserControls from within a Form. The following Sub-Routine exists in my Windows application.

    Private Sub BuildChannelControlTabs()
        Try
            EH.ErrorMessage = String.Empty

            If tabTests.TabPages.Contains(tabChannels) Then
                For x As Integer = 0 To stcChannels.Length - 1
                    Dim tab As New TabPage
                    Dim uC1 As New userChannelSettings

                    uC1.Name = "ucChannel" & x + 1
                    uC1.Tag = stcChannels(x).channel_ID
                    tab.Controls.Add(uC1)
                    uC1.ForeColor = tab.ForeColor

                    AddHandler uC1.Load, AddressOf ucChannel_Load

                    tab.Name = "tChannel" & x + 1
                    tab.Tag = stcChannels(x).channel_ID
                    tab.Text = "Channel: " & stcChannels(x).channel

                    If Not tabChannelList.TabPages.Contains(tab) Then
                        tabChannelList.TabPages.Add(tab)
                    End If
                Next
            Else
                EH.ErrorMessage = "Invalid Control Creation!" & "~E"
                GoTo ProcessMessage
            End If

            If tabTests.TabPages.Contains(tabEquipmentByChannel) Then
                For x As Integer = 0 To stcChannels.Length - 1
                    Dim tab As New TabPage
                    Dim uC2 As New userChannelEquipment()

                    uC2.Name = "ucEquipment" & x + 1
                    uC2.Tag = stcChannels(x).channel_ID
                    uC2.Location = New Point(5, 5)
                    tab.Controls.Add(uC2)
                    uC2.ForeColor = tab.ForeColor

                    AddHandler uC2.Load, AddressOf ucEquipment_Load

                    tab.Name = "tEquip" & x + 1
                    tab.Tag = stcChannels(x).channel_ID
                    tab.Text = "Channel: " & stcChannels(x).channel

                    If Not tabChannelEquipment.TabPages.Contains(tab) Then
                        tabChannelEquipment.TabPages.Add(tab)
                    End If
                Next
            Else
                EH.ErrorMessage = "Invalid Control Creation!" & "~E"
            End If

ProcessMessage:

        Catch ex As Exception
            EH.ErrorMessage = "frmCalibration_3/BuildChannelControlTabs() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try
    End Sub

Open in new window


Using the above code, two UserControls are created: uC1 and uC2 with assigned names of ucChannel? and ucEquipment1? respectively. Each instance of these controls are placed on its own TabPage, which is created in the Designer. So, 12 UC's = 12 TabPages.

How can I access ucChannel? and ucEquipment? from within other Functions/SubRoutines within the same Form?

Code examples would greatly be appreciated.

Thanks!
BlakeMcKennaAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
One option would be to add a couple of Lists to the Form and add the dynamic instances to them:
    Private uC1s As New List(Of userChannelSettings)
    Private uC2s As New List(Of userChannelEquipment)

    Private Sub BuildChannelControlTabs()
        Try
            EH.ErrorMessage = String.Empty

            If tabTests.TabPages.Contains(tabChannels) Then
                For x As Integer = 0 To stcChannels.Length - 1
                    Dim tab As New TabPage
                    Dim uC1 As New userChannelSettings

                    uC1s.Add(uC1)

                    ...

                Next
            Else
                EH.ErrorMessage = "Invalid Control Creation!" & "~E"
                GoTo ProcessMessage
            End If

            If tabTests.TabPages.Contains(tabEquipmentByChannel) Then
                For x As Integer = 0 To stcChannels.Length - 1
                    Dim tab As New TabPage
                    Dim uC2 As New userChannelEquipment()

                    uC2s.Add(uC2)

                    ...

                Next
            Else
                EH.ErrorMessage = "Invalid Control Creation!" & "~E"
            End If

ProcessMessage:

        Catch ex As Exception
            EH.ErrorMessage = "frmCalibration_3/BuildChannelControlTabs() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try
    End Sub

Open in new window


Then you can access them with "uC1s(index)" and "uC2s(index)" from anywhere in the form.

You could also use a Dictionary instead, using the control name as the key.
BlakeMcKennaAuthor Commented:
Mike,

If, at design time, I add a single UserControl to a tabpage, but then when I run the application, I remove the same tabpages. At some point, the user has the option to add the same tabpage back onto the tab control. When this happens the UserControl is not present. Shouldn't the UC stay on the tabpage even though it is removed at runtime?
BlakeMcKennaAuthor Commented:
Mike,

I tried what you suggested and I tested it but looping through the control on the UC. Each UC has 4 groupbox controls in which resides another UC. Do I need to access this UC by first prefacing it with the groupbox? For example:

groupBox1.userEnvironment.txtMeasured

Is there a better way?
Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
If that's the way they are setup, then that should work.  Without having the app in front of me, and a better understanding of all the code, I can't really know if there is a "better" way.
BlakeMcKennaAuthor Commented:
Mike,

I have attached a Screenshot of the UI in designer mode. Hopefully that will give you a more clearer picture of what's going on. Below is the code, that add's the tabPages back onto the Tab Control. There are two For Loops, one is for the "Channels" TabPage and the other is for the "Equipment By Channel" TabPage.

    Private Sub BuildChannelControlTabs()
        Try
            EH.ErrorMessage = String.Empty

            If tabTests.TabPages.Contains(tabChannels) Then
                For x As Integer = 0 To stcChannels.Length - 1
                    Dim tab As New TabPage

                    tab.Name = "tChannel" & x + 1
                    tab.Tag = stcChannels(x).channel_ID
                    tab.Text = "Channel: " & stcChannels(x).channel

                    If Not tabChannelList.TabPages.Contains(tab) Then
                        tabChannelList.TabPages.Add(tab)
                    End If
                Next
            Else
                EH.ErrorMessage = "Invalid Control Creation!" & "~E"
                GoTo ProcessMessage
            End If

            If tabTests.TabPages.Contains(tabEquipmentByChannel) Then
                For x As Integer = 0 To stcChannels.Length - 1
                    Dim tab As New TabPage

                    tab.Name = "tE" & x + 1
                    tab.Tag = stcChannels(x).channel_ID
                    tab.Text = "Channel: " & stcChannels(x).channel

                    If Not tabChannelEquipment.TabPages.Contains(tab) Then
                        tabChannelEquipment.TabPages.Add(tab)
                    End If
                Next
            Else
                EH.ErrorMessage = "Invalid Control Creation!" & "~E"
            End If

ProcessMessage:

        Catch ex As Exception
            EH.ErrorMessage = "frmCalibration_3/BuildChannelControlTabs() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try
    End Sub

Open in new window

Screenshot.jpg
ArkCommented:
You can just "hide" tab pages
    Private Class pageData
        Public Property index As Integer
        Public Property key As String
        Public Property Visible As Boolean
        Public Property Page As TabPage
    End Class

    Private hiddenPages As New List(Of pageData)

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        For i = 0 To TabControl1.TabPages.Count - 1
            Dim tp = TabControl1.TabPages(i)
            hiddenPages.Add(New pageData With {.Page = tp, .Visible = False, .index = i, .key = tp.Name})
        Next
        TabControl1.TabPages.Clear()
    End Sub
    Private Sub ShowPage(key As String)
        Dim pd = (From x In hiddenPages Where x.key = key).FirstOrDefault
        If pd Is Nothing OrElse pd.Visible Then Return
        TabControl1.TabPages.Insert(pd.index, pd.Page)
        ' Dim ctrl =pd.Page.Controls(0)
        ' If Type Of ctrl Is userChannelSettings Then
        '     Dim uc = CType(ctrl, userChannelSettings)
        '     uc.Tag = ....
        ' ElseIf Type Of ctrl Is userChannelEquipment Then
        '     Dim uc = CType(ctrl, userChannelEquipment)
        '     uc.Tag = ....
        ' End If
        pd.Visible = True
    End Sub

    Private Sub HidePage(key As String)
        Dim pd = (From x In hiddenPages Where x.key = key).FirstOrDefault
        If pd Is Nothing OrElse pd.Visible = False Then Return
        TabControl1.TabPages.Remove(pd.Page)
        pd.Visible = False
    End Sub

Open in new window

If you need update user control's properties you can do this in ShowPage sub (see commented lines).

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
BlakeMcKennaAuthor Commented:
Thanks Ark...I did not know that TabPages could be hidden...
ArkCommented:
Actually, they cannot be hidden (see quotes around "hide") :)
You can create a list of tab pages (incapulated in a class with some extra properties) and then just insert/remove those pages into tab control instead of show/hide
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.