Hi,

There are 50+ textboxes and comboboxes on my form and I created a label to store the tag of each textbox or combobox as it is focused.

This is portion of what I had currently.

Private Sub cmbCGWPBCl1t_GotFocus()
    Forms!Main!lblMessage.Caption = Me!cmbCGWPBCl1t.Tag
End Sub

Private Sub txtSUHal_GotFocus()
    Forms!Main!lblMessage.Caption = Me!txtSUHal.Tag
End Sub

Would anyone show me how I can put them all into a loop using the for loop?

For Each ctl In Me.Controls
    --- codes ---
Next ctl

Thanks in advance for the help!

Recommended Answers

Try

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    For Each tbx As TextBox In Me.Controls.OfType(Of TextBox)()
        AddHandler tbx.Enter, AddressOf TextBox_Enter
    Next

End Sub

Private Sub TextBox_Enter(sender As System.Object, e As System.EventArgs)
    Dim tbx As TextBox = sender
    lblMessage.Caption = tbx.Tag
End Sub

Use …

Jump to Post

What error does it throw?

Jump to Post

All 5 Replies

Try

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    For Each tbx As TextBox In Me.Controls.OfType(Of TextBox)()
        AddHandler tbx.Enter, AddressOf TextBox_Enter
    Next

End Sub

Private Sub TextBox_Enter(sender As System.Object, e As System.EventArgs)
    Dim tbx As TextBox = sender
    lblMessage.Caption = tbx.Tag
End Sub

Use the same for ComboBox.

Thanks for the quick response. I'm a very new vb programmer, my apologies.
For some reason, << For Each tbx As TextBox In Me.Controls.OfType(Of TextBox)() >> throws out an error.

What error does it throw?

This is the vb under ms access. It turns red and suggest to replace "as" to "in". thanks.

That's not vb.net then. It's vba. You are in the wrong forum.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.