【问题标题】:How can I add a custom control inherited from an existing one, then be able to retrieve it?如何添加从现有控件继承的自定义控件,然后能够检索它?
【发布时间】: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


【解决方案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)

【讨论】:

  • 我怎么错过了。非常感谢。很明显,我在上下文中创建了 frm 并且以后从未引用过相同的表单。
猜你喜欢
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
相关资源
最近更新 更多