利用递归,动态创建带有层级关系控件,解决了父子关系控件的创建问题
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GenerateControl()
End Sub
Private Sub GenerateControl()
Dim table As New DataTable()
Dim strCon As String = "server=.;database=dynamiccontrol;integrated security=true;"
Dim conn As New SqlConnection(strCon)
Dim sql As String = "select * from test"
Dim cmd As New SqlCommand(sql, conn)
Dim da As New SqlDataAdapter(cmd)
da.Fill(table)
'预览数据
DataGridView1.DataSource = table
Dim view As New DataView(table)
view.RowFilter = "fid =0 "
For Each row As DataRowView In view
Dim assemblyQualifiedName As String = GetType(System.Windows.Forms.Form).AssemblyQualifiedName
Dim assemblyInformation As String = assemblyQualifiedName.Substring(assemblyQualifiedName.IndexOf(","))
Dim t As Type = Type.GetType(row("ctltype").ToString() & assemblyInformation)
Dim control As Control = DirectCast(System.Activator.CreateInstance(t), Control)
control.Location = New System.Drawing.Point(CInt(row("pointx")), CInt(row("pointy")))
control.Name = row("ename").ToString
control.Text = row("cname").ToString
control.Size = New System.Drawing.Point(CInt(row("sizew")), CInt(row("sizeh")))
control.BackColor = Color.Coral
Me.Controls.Add(control)
AddChildItems(table, row("id").ToString(), control)
Next row
End Sub
Private Sub AddChildItems(ByVal table As DataTable, ByVal id As String, ByVal obj As Control)
Dim viewItem As New DataView(table)
viewItem.RowFilter = "fid=" & id
For Each childView As DataRowView In viewItem
Dim assemblyQualifiedName As String = GetType(System.Windows.Forms.Form).AssemblyQualifiedName
Dim assemblyInformation As String = assemblyQualifiedName.Substring(assemblyQualifiedName.IndexOf(","))
Dim t As Type = Type.GetType(childView("ctltype").ToString() & assemblyInformation)
Dim control As Control = DirectCast(System.Activator.CreateInstance(t), Control)
control.Location = New System.Drawing.Point(CInt(childView("pointx")), CInt(childView("pointy")))
control.Name = childView("ename").ToString
control.Text = childView("cname").ToString
control.Size = New System.Drawing.Point(CInt(childView("sizew")), CInt(childView("sizeh")))
control.BackColor = Color.Beige
obj.Controls.Add(control)
AddChildItems(table, childView("id").ToString, obj)
Next childView
End Sub
End Class