我想动态地将一个usercontrol添加到VB.Net中的表单中。我将从数据库中提取UserControl名称(String),如果项目中存在UserControl,我希望将其添加到表单中。 我知道如何以编程方式将usercontrols添加到表单中,但我不确定如何使用字符串作为名称。
Dim userContName As UserControl = dtModules.Rows(k).Item("uc_Name")
Panel1.Controls.Add(userContName)
我试图这个灵魂
Public Sub LoadGroups()
dtModules = Tbl_GroupModulesTableAdapter1.GetDataBy_spGetModuleByGroup(grp.Name)
For k = 0 To dtModules.Rows.Count - 1
If grp.Name = dtModules.Rows(k).Item("Module_Group") Then
Dim fullyQualifiedClassName As String = dtModules.Rows(k).Item("Module_Name")
If fullyQualifiedClassName = Nothing Then
Else
Dim o = fetchInstance(fullyQualifiedClassName)
Dim b = CType(o, Control)
grp.Controls.Add(b)
End If
End If
Next
End Sub
Public Function fetchInstance(ByVal fullyQualifiedClassName As String) As Object
Dim nspc As String = fullyQualifiedClassName.Substring(0, fullyQualifiedClassName.LastIndexOf("."c))
Dim o As Object = Nothing
Try
For Each ay In Assembly.GetExecutingAssembly().GetReferencedAssemblies()
If (ay.Name = nspc) Then
o = Assembly.Load(ay).CreateInstance(fullyQualifiedClassName)
Exit For
End If
Next
Catch
End Try
Return o
End Function
答案 0 :(得分:1)
好的,可以使用它;
Dim ucName As String = Projectname.UserControlName
Dim newType As Type = Type.[GetType](ucName, True, True)
Dim o As Object = Activator.CreateInstance(newType)
Form.Controls.Add(o)
一旦我得到它,这很简单!感谢您的反馈!