An object-oriented programming language developed by Microsoft that can be used in .NET.
Hi,
you can save all UserControls in List and then call PerformClick for selected UserControl. Try following demo:
Public Class Form30
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Height = 1200
Me.Width = 800
Me.Controls.AddRange(New Control() {ComboBox1, ComboBox2, BtnCreateUserControlInstance})
Me.cbBS1.DataSource = buttons
Me.cbBS2.DataSource = buttons
Me.ComboBox1.DataSource = Me.cbBS1
Me.ComboBox2.DataSource = Me.cbBS2
End Sub
Private WithEvents BtnCreateUserControlInstance As New Button With {.Text = "BtnCreateUserControlInstance", .Top = 5, .Width = 200}
Private WithEvents ComboBox1 As New ComboBox With {.Top = 5, .Left = 210, .DisplayMember = "Header", .Tag = "Button1"}
Private WithEvents ComboBox2 As New ComboBox With {.Top = 5, .Left = 350, .DisplayMember = "Header", .Tag = "Button2"}
Private index As Integer = 1
Private buttons As New List(Of myUserControl)
Private cbBS1 As New BindingSource
Private cbBS2 As New BindingSource
Private Sub BtnCreateUserControlInstance_Click(sender As Object, e As EventArgs) Handles BtnCreateUserControlInstance.Click
Dim uc As New myUserControl With {.Header = $"myUserControl{index}", .Top = index * 50, .Width = 400, .Height = 50}
Me.Controls.Add(uc)
Me.buttons.Add(uc)
Me.cbBS1.ResetBindings(False)
Me.cbBS2.ResetBindings(False)
index = index + 1
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged, ComboBox2.SelectedIndexChanged
Dim cb = TryCast(sender, ComboBox)
If cb Is Nothing Then Exit Sub
Dim uc = TryCast(cb.SelectedItem, myUserControl)
If uc Is Nothing Then Exit Sub
If cb.Tag.ToString = "Button1" Then
uc.Button1.PerformClick()
Else
uc.Button2.PerformClick()
End If
End Sub
Public Class myUserControl
Inherits UserControl
Public Sub New()
AddHandler Me.Load, AddressOf Uc_Load
End Sub
Private Label1 As New Label With {.Top = 0, .Left = 5, .Width = 100}
Friend WithEvents Button1 As New Button With {.Text = "Button1", .Top = 0, .Left = 120, .Width = 100}
Friend WithEvents Button2 As New Button With {.Text = "Button2", .Top = 0, .Left = 240, .Width = 100}
Private TextBox1 As New TextBox With {.Top = 25, .Left = 5, .Width = 150}
Private TextBox2 As New TextBox With {.Top = 25, .Left = 160, .Width = 150}
Public Property Header As String
Private Sub Uc_Load(sender As Object, e As EventArgs)
Me.Controls.AddRange(New Control() {Label1, Button1, Button2, TextBox1, TextBox2})
Label1.DataBindings.Add("Text", Me, "Header")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = Now.ToLongTimeString
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox2.Text = Now.ToLongTimeString
End Sub
End Class
End Class
Result: