2017-06-30 108 views
-1

我想在VB.Net中動態添加一個usercontrol到表單。我將從數據庫中拉取UserControl名稱(字符串),如果該項目中存在UserControl,我希望將它添加到表單中。 我知道如何以編程方式將用戶控件添加到窗體,但我不知道如何使用字符串作爲名稱。動態添加UserControl到表格

Dim userContName As UserControl = dtModules.Rows(k).Item("uc_Name") 
Panel1.Controls.Add(userContName) 

我嘗試這個soultion

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

[Visual Basic:使用字符串作爲名稱動態創建對象]的可能重複(https://stackoverflow.com/questions/3432317/visual-basic-dynamically-create-objects-using-a-string-as -名字) –

回答

0

確定了它與這個工作;

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) 

一旦我得到它,它非常簡單!感謝您的反饋!