通过名称调用外部用户控件

时间:2012-11-11 15:18:32

标签: vb.net winforms user-controls panel

我有一个面板(Panel1),两个组合框(ComboBox1ComboBox2)和一个按钮(Button1)都采用相同的形式({{1} })。

单击按钮时:

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中向p1k1添加名为Panel1的外部用户控件吗?

Form1

我该怎么做才能使这项工作?

通常我会使用:

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

2 个答案:

答案 0 :(得分:0)

您需要使用reflection来执行此操作。像这样:

    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

答案 1 :(得分: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)
  结束Sub