How to access public subs of dynamically loaded user control in a panel

后端 未结 1 1611
一整个雨季
一整个雨季 2021-01-29 06:10

I have a panel and a button in a form and 2 user controls, I dynamically loaded the first user control in the panel then inside the userControl1 I have a method that I want to a

相关标签:
1条回答
  • 2021-01-29 06:44

    OK, I'll take as much as I can from your question and show you an example, there are many different ways you could do this, thus, may not answer your question 100% but will give you enough to get what you want.

    I'm making an assumption that you only have one control1 and one control2.

    My example will alternate, and access a sub routine in the active (shown) usercontrol on each click on the main form button.

    In a module I would put:

    Public control1 As New UserControl1
    Public control2 As New UserControl2
    

    In UserControl1 put:

    Public Sub DoSomething()
        Me.BackColor = Color.Black
    End Sub
    

    In UserControl2 put:

    Public Sub DoSomething()
        Me.BackColor = Color.White
    End Sub
    

    In your FormLoad event put:

        control1.Location = New Point(0, 0)
        control1.Size = New Point(1351, 533)
        Panel1.Controls.Add(control1)
    

    In your Button1 click event put:

        Select Case Panel1.Contains(control1)
            Case True
                'Remove UserControl1 - Add UserControl2
                Panel1.Controls.Remove(control1)
                control2.Location = New Point(0, 0)
                control2.Size = New Point(1351, 533)
                Panel1.Controls.Add(control2)
                control2.DoSomething()
            Case False
                'Remove UserControl2 - Add UserControl1
                Panel1.Controls.Remove(control2)
                control1.Location = New Point(0, 0)
                control1.Size = New Point(1351, 533)
                Panel1.Controls.Add(control1)
                control1.DoSomething()
        End Select
    

    The above is checking which UserControl is in the panel and alternating it and calling the 'DoSomething'. This is just an example to give you an idea. What you want may be different, you may have a button in your second UserControl and if so, amend the switch code to suit.

    0 讨论(0)
提交回复
热议问题