Search code examples
.netvb.netwinformsstring-interning

Checking the Tags of each TextBox in an array


How do I check the Tag property of all the TextBox controls in an array?
I want something like this:

If textBox.Tag And textbox2.Tag And textbox21.Tag And
   textbox22.Tag And textbox23.Tag And textbox24.Tag = "2" Then

This is my array of TextBoxes:

Dim allTextboxes() As TextBox = {textBox, narNaslov, narPersona, narDani, narPersona2,
                                 kupIme, kupAdresa, kupKontakt, uvBroj, uvDatum, uvIznos,
                                 uvAvans, uvRok, uvNacin, datumTbox} 

Solution

  • You can use the LINQ All()-Method

    If allTextBoxes.All(Function(t) t.Tag.ToString = "2") Then
        'All Tags are "2"
    End If
    

    To avoid a NullReferenceException, if one of the textboxes is Nothing you can add an additional check:

    If allTextBoxes.All(Function(t) t IsNot Nothing AndAlso t.Tag.ToString = "2") Then
        'All Tags are "2"
    End If
    

    Or you can use the Null-conditional operator (Visual Basic v. 14 or greater)

    If allTextBoxes.All(Function(t) t?.Tag.ToString = "2") Then
        'All Tags are "2"
    End If