Deathonly Deathonly - 2 months ago 8x Question

AllTextBox event in TextChanged

Hello This is a code of mine

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
TextBox1.Text = Val(TextBox1.Text)
End Sub

Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
TextBox2.Text = Val(TextBox2.Text)
End Sub

Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged
TextBox3.Text = Val(TextBox3.Text)
End Sub

Private Sub TextBox4_TextChanged(sender As Object, e As EventArgs) Handles TextBox4.TextChanged
TextBox4.Text = Val(TextBox4.Text)
End Sub

Private Sub TextBox5_TextChanged(sender As Object, e As EventArgs) Handles TextBox5.TextChanged
TextBox5.Text = Val(TextBox5.Text)
End Sub

Private Sub TextBox6_TextChanged(sender As Object, e As EventArgs) Handles TextBox6.TextChanged
TextBox6.Text = Val(TextBox6.Text)
End Sub

How do i make a short code for all textboxes ?
I try with this code i didn't work

Dim i As integr
TextBox(i).text = Val(TextBox(i).text)

Thanks for any help


You only need to create one TextChanged handler and then bind all your Texbox events to it.

Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) _
        Handles TextBox1.TextChanged, TextBox2.TextChanged, <...for all your textboxes ..>
    Dim target = DirectCast(sender, TextBox)
    target.Text = Val(target.Text)
End Sub

If you want to bind all textboxes in code, you can do this programatically once your form has loaded:

Dim allTextBoxes = Me.Controls.OfType(Of TextBox)()
For Each textbox In allTextBoxes = 
    AddHandler textbox.TextChanged, AddressOf TextBox_TextChanged