Select all textbox text

Asked

Viewed 296 times

0

I have the following code:

Private Sub nct_focus(sender As Object, e As EventArgs) Handles nCT.GotFocus, nCT.Click
    sender.SelectAll()
End Sub

what happens is this, it works well, however I have some 40 textboxes in my form, I already took a look and I would like to call this function in all textboxes of my form...

some way to do this without having to repeat the code every time you include a new textbox?

1 answer

1


Just add the elements that will have the events treated (handled) by separating by commas:

Private Sub nct_focus(sender As Object, e As EventArgs) Handles text1.GotFocus, text2.GotFocus, text2.GotFocus.... etc....
    sender.SelectAll()
End Sub

Now if you want to automatically all the Textboxes of your form have the event associated with your method, you can search all the elements within your form, in Collection Controls, check if not of the type TextBox and associate the event.

You can do this by loading the form, something like that:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
   ' Para cada controle, verificar o tipo e associar ao evento
    For Each ctrl As Control In Me.Controls

        If TypeOf ctrl Is TextBox Then
            Dim textBox As TextBox = CType(ctrl, TextBox)
            AddHandler textBox.GotFocus, AddressOf nct_focus
        End If
    Next
End Sub
  • in the first way I already knew that I could do, I wanted something close to the second form, however I had tested this way that you passed, unfortunately it did not work

  • what didn’t work? he didn’t associate the events, or associate and didn’t do what he expected?

  • did not associate the events, I think the output will be do as in the first way

  • got.... just to confirm, if converting Sender does not work? on that line sender.SelectAll() Sender is an Object, no need to convert to TextBox?

  • I managed to make it work, it was an error of my analysis, there was a tabcontrol inside my form, which made the event was not added, because there was no textbox directly in the form, but in the tabcontrol.

  • 1

    Cool, this reminds me of a lot of things, it’s been a while since I’ve worked with Forms.. Good luck :)

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.