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

南楼画角 提交于 2019-12-02 13:15:36

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!