【问题标题】:Calling external user control by its name按名称调用外部用户控件
【发布时间】:2012-10-31 05:06:45
【问题描述】:

我有一个面板 (Panel1)、两个组合框 (ComboBox1ComboBox2) 和一个按钮 (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。 我可以使用以下方法在Form1 中添加一个名为p1k1 的外部用户控件到Panel1 吗?

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

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

通常我会使用:

Panel1.Controls.Add(new p1k1)

【问题讨论】:

标签: vb.net winforms user-controls panel


【解决方案1】:

我终于找到了答案……

Private Sub AddUserControl(ByVal 作为字符串)
将 nmspace 调暗为 String = "mynamespace"
Dim t As Type = Assembly.GetExecutingAssembly().GetType(nmspace & "." & a)
Dim o As Control = Activator.CreateInstance(t)
Panel1.Controls.Add(o)
结束子

【讨论】:

    【解决方案2】:

    您需要使用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
    

    【讨论】:

    • 我得到了 newControl 变量的空值
    • 这意味着:1) "a" 引用的字符串不是有效的类型名称或 2) 该类型不是从 Control 继承的(因此不能添加到 Control 集合中)。检查我添加了简单类型检查的编辑代码。
    • 出现异常号 1,不是有效的类型名称...如何解决这个问题?我的项目解决方案中的用户控件文件名是 p1k1.vb .... 为什么说它不是有效的类型名称?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多