通过执行以下操作,我创建了一个继承自TextBox类的新类:
Public Class mTextBox
Inherits TextBox
Dim field As String
Public Property FieldName()
Get
Return field
End Get
Set(ByVal value)
field = value
End Set
End Property
End Class
然后我创建了一组动态mTextBox
es并将它们添加到表单中,方法是:
Dim frm As New Form
Dim mtb As New mTextBox
mtb.Text = "my text"
mtb.FieldName = "field_name"
frm.controls.add(mtb)
mtb.SetBounds(20, 20, 100, 20)
frm.Show()
工作正常,我可以看到文本框出现在表单上。
但是当我尝试遍历表单上的所有控件以获取.Text
和.FieldName
时,没有检测到任何控件,因此不会执行单个迭代。这是我的代码,它遍历表单上的所有控件
Sub savecustomer()
Dim fields As String = ""
Dim values As String = ""
For Each t In Me.Controls
If TypeOf (t) Is mTextBox Then
Dim TB As mTextBox = DirectCast(t, mTextBox)
fields &= TB.FieldName & ","
values &= "'" & TB.Text & "',"
End If
Next
fields = fields.Substring(0, fields.Length - 1)
values = values.Substring(0, values.Length - 1)
Dim sql As String = String.Format("insert into customers ({0}) values ({1})", fields, values)
Execute_SQL(sql)
End Sub
我尝试稍微更改for循环:
For Each t In Me.Controls
If TypeOf (t) Is TextBox Then
Dim TB As mTextBox = DirectCast(t, mTextBox) 'This line throws exception
'The exception is : cannot cast TextBox to mTextBox
fields &= TB.FieldName & ","
values &= "'" & TB.Text & "',"
End If
Next
如果我通过用TextBox替换每个mTextBox来更改上面的代码,那么代码将起作用但我将失去获取.FieldName的能力,因为它不是TextBox的成员
我做错了什么?
答案 0 :(得分:1)
您需要参考正确的表格。当您创建新表单Dim frm As New Form
时,它没有名为savecustomer
的方法。
Sub savecustomer()
For Each t In Me.Controls '<- NOT frm
Next
End Sub
更改保存方法以包含Form
参数:
Sub savecustomer(frm As Form)
For Each t In frm.Controls
'...
Next
End Sub
然后将您要保存的表单传递给savecustomer
:
Dim frm As New Form
'...
savecustomer(frm)