Search code examples
vb.netbasic

VB.NET Create a dynamic textbox and have a different function


So here I'm trying to create a dynamic textbox that has a different function per-textbox but sadly the message box is not working I'm studying selft studying this one and I'm having a hard time. Can anyone tell me what have i done wrong with this one?

 Public Function AddNewTextBox() As System.Windows.Forms.TextBox
    Dim txt As New System.Windows.Forms.TextBox()
    Me.Controls.Add(txt)
    txt.Top = cLeft * 25
    txt.Left = 100
    txt.Text = "TextBox " & Me.cLeft.ToString
    txt.Name = "TextBox" & Me.cLeft.ToString
    cLeft = cLeft + 1
    Return txt
    AddHandler txt.TextChanged, AddressOf Me.text_change


    Dim txt1 As New System.Windows.Forms.TextBox()
    Me.Controls.Add(txt1)
    txt1.Top = cLeft * 15
    txt1.Left = 90
    txt1.Text = "1 " & Me.cLeft.ToString
    txt1.Name = "TextBox" & Me.cLeft.ToString
    cLeft = cLeft + 1
    Return txt
    AddHandler txt1.TextChanged, AddressOf Me.text1_change
End Function

Private Sub text_change(ByVal sender As System.Object, ByVal e As System.EventArgs)
    MessageBox.Show("The First Text has Been Change.")
End Sub

Private Sub text1_change(ByVal sender As System.Object, ByVal e As System.EventArgs)
    MessageBox.Show("The Second Text has Been Change.")
End Sub

Solution

  • Look at the 9th line of the code you posted:

    Return txt
    

    When execution hits that line the method completes and no subsequent lines of code are executed. That means that the event handler is not attached to the first TextBox and the second one isn't even created.

    Why are you returning anything in the first place? You're creating two TextBoxes so how does it make sense to return one of them? Make the method a Sub and get rid of the Return statements or else return both TextBoxes together in an array or the like at the end of the method.