Ahmad
Ahmad

Reputation: 12737

How can I add a custom control inherited from an existing one, then be able to retrieve it?

I have created a new class that inherits from TextBox class, by doing:

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

I then created a set of dynamic mTextBoxes and added them onto a form, by doing:

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()

That works fine and I am able to see the textbox appearing on the form. But when I try to iterate through all of the controls on the form to fetch the .Text and .FieldName, no control is detected, so no single iteration is executed. Here is my code that iterates through all controls on the form

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

I tried changing the for loop a bit:

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

If I change the above code by replacing each mTextBox with TextBox then the code will work but I would lose the ability to fetch the .FieldName since it is not a member of TextBox

What am I doing wrong?

Upvotes: 0

Views: 257

Answers (1)

You need to refer to the right form. When you create the new form Dim frm As New Form it doesn't have a method named savecustomer.

Sub savecustomer()
    For Each t In Me.Controls '<- NOT frm
    Next
End Sub

Change your save method to include a Form parameter:

Sub savecustomer(frm As Form)
    For Each t In frm.Controls
        '...
    Next
End Sub

Then pass the form you wish to save to savecustomer:

Dim frm As New Form
'...
savecustomer(frm)

Upvotes: 1

Related Questions