0

我有一个面板 ( Panel1)、两个组合框 ( ComboBox1, ComboBox2) 和一个按钮 ( Button1),所有这些都采用相同的形式 ( Form1)。

单击按钮时:

Private Sub Button1_Click(sender As Object, e As EventArgs)
   Dim a as String = ComboBox1.SelectedValue() & Combobox2.SelectedValue()
   AddUserControl(a)
End Sub

的值a是外部用户控件的名称,例如p1k1。我可以使用以下方法添加一个名为p1k1toPanel1的外部用户控件吗?Form1

Private Sub AddUserControl(ByVal a As String)
    Panel1.Controls.Add(a)
End Sub

我应该怎么做才能完成这项工作?

通常我会使用:

Panel1.Controls.Add(new p1k1)
4

2 回答 2

0

您需要使用反射来执行此操作。像这样的东西:

    Private Sub AddUserControl(ByVal a As String)
        Dim controlType As Type = Type.GetType(a)
        If controlType Is Nothing Then
            Throw New ArgumentException(String.Format("""{0}"" is not a valid type.  Type names are case sensitive.", a))
        ElseIf Not controlType.IsSubclassOf(GetType(Control)) Then
            Throw New ArgumentException(String.Format("""{0}"" does not inherit from Control.  Only Controls can be added to the control collection.", a))
        End If

        Dim newControl As Control = Activator.CreateInstance(controlType)
        If newControl Is Nothing Then
            Throw New ArgumentException(String.Format("Unspecified error when creating control of type ""{0}"".", a))
        End If
        Panel1.Controls.Add(newControl)
    End Sub
于 2012-11-11T19:51:50.603 回答
0

我终于找到了答案……

Private Sub AddUserControl(ByVal a As String)
Dim nmspace As String = "mynamespace"
Dim t As Type = Assembly.GetExecutingAssembly().GetType(nmspace & "." & a)
Dim o As Control = Activator.CreateInstance(t)
Panel1 .Controls.Add(o)
End Sub

于 2012-11-12T16:46:53.610 回答