0

I'm using .NET Framework 4.7.2 for reference.

I'm using Me.Controls.OfType for automated handles in an event in my form.

Sub AddTextBoxes_TextChanged()
    Dim textboxes = Me.Controls.OfType(Of TextBox)()

    Console.WriteLine(textboxes.Count)
    For Each txt In textboxes
        AddHandler txt.TextChanged, AddressOf AllTextBoxes_TextChanged
    Next
End Sub

Private Sub SampleForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    AddTextBoxes_TextChanged()
End Sub

Private Sub AllTextBoxes_TextChanged(sender As Object, e As EventArgs)
    ' ...
End Sub

However, the For loop doesn't work, so I checked if there are actual textbox controls within textboxes with Console.WriteLine(textboxes.Count). Well, the result is 0. I've checked multiple times in the Form Design for textboxes, and they exist. Why doesn't Controls.OfType(Of TextBox)() work?

  • 4
    Are your texboxes contained in the Form (Me) or are they inside some other container? (GroupBox, Panel, etc) – Steve May 30 '21 at 08:47
  • Oh I didn't think about that... How do I get the textboxes within a GroupBox? – unovillegas May 30 '21 at 08:48
  • 2
    @UnoVillegas https://stackoverflow.com/questions/3419159/how-to-get-all-child-controls-of-a-windows-forms-form-of-a-specific-type-button – Dai May 30 '21 at 08:49
  • The easiest way is with drag and drop in the form designer. Or just creating them in the groupbox surface – Steve May 30 '21 at 08:49

1 Answers1

0

Place your handler in the code for the form. In design view select the one of the text boxes. In the Properties window select the lightning bolt to display all the events available for a TextBox. Choose the TextChanged event and the drop down box arrow. Your AllTextBoxes_TextChanged method will be listed because the signature matches. Select your method and the Handles code will be added to the method. Do the same for each text box you wish to use this method.

Of course you can always type the extended Handles clause.

However, I don't see what is wrong with your code.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim textboxes = Controls.OfType(Of TextBox)() '.ToList
    For Each txt In textboxes
        AddHandler txt.TextChanged, AddressOf AllTextBoxes_TextChanged
    Next
End Sub

Private Sub AllTextBoxes_TextChanged(sender As Object, e As EventArgs)
    Dim tb = DirectCast(sender, TextBox)
    MessageBox.Show($"The text changed event fired by {tb.Name}")
End Sub

Works for me.

Mary
  • 14,926
  • 3
  • 18
  • 27