【发布时间】:2014-01-15 09:30:42
【问题描述】:
我创建了一个继承自 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
然后我创建了一组动态 mTextBoxes 并将它们添加到表单中,方法是:
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
如果我通过将每个 mTextBox 替换为 TextBox 来更改上述代码,那么代码将起作用,但我将失去获取 .FieldName 的能力,因为它不是 TextBox 的成员
我做错了什么?
【问题讨论】:
-
SameCustomer 方法在哪里?
-
@MattWilko 你是说 SaveCustomer 吗?我在同一个表单代码页上声明了它
-
反正这类问题通常不是通过继承Controls来解决的。您可以使用 Dictionary(Of TextBox, String) 并将 TextBox 绑定到它们的值(您甚至可以绑定到类/结构)
标签: .net vb.net inheritance custom-controls