关于动态地在窗口上创建控件的问题
各位好!,
我刚接触VB.NET,菜啊...
预设有表
字段:fieldname fname_ch ctltype
值: cName 名称 textbox
...
我的思路是:
遍历表,读取记录信息生成控件
如上面这条记录,一般情况下可以写成
Dim mcontrol As textbox = New textbox
现在问题是 "textbox "是从表中读取的变量的值
请问这条语句应该怎么写呢?
...
Dim dr As SqlDataReader = cmdsql.ExecuteReader
While dr.Read
Dim mfname As String = dr.Item(1)
Dim mfname_ch As String = dr.Item(2)
Dim mctltype As String = dr.Item(3)
'请问以下这句怎么写?
Dim mcontrol As ? = New ?
End While
...
请知道的兄弟赐教,不胜感激!
[解决办法]
http://www.qqread.com/csharp/u587187002.html
这里写的就是你要的情况,不过我试了一下不行....不明白了.
[解决办法]
如果需要通过字符串来创建类的话,是需要用到反射机制的。
下面是我根据别人的代码改成的VB.Net格式:
Public Sub Create_Control(ByVal controlType As String, ByVal form As Form, ByVal positionX As Integer, ByVal positionY As Integer)
Try
Dim assemblyQualifiedName As String = GetType(System.Windows.Forms.Form).AssemblyQualifiedName
Dim assemblyInformation As String = assemblyQualifiedName.Substring(assemblyQualifiedName.IndexOf( ", "))
Dim ty As Type = Type.GetType(controlType + assemblyInformation)
Dim newControl As Control = CType(System.Activator.CreateInstance(ty), Control)
form.SuspendLayout()
newControl.Location = New System.Drawing.Point(positionX, positionY)
newControl.Name = ty.Name + form.Controls.Count.ToString()
form.Controls.Add(newControl)
form.ResumeLayout()
Catch ex As Exception
MsgBox( "Faild to Control! ")
End Try
End Sub
调用示例 Create_Control( "System.Windows.Forms.TextBox ", Me, 10, 10)