1

very simple question, how to combine and or operators into the same statement.

c.GetType is getType(TextBox) AND foo or bar or baz

this is not working

For Each c As Control In Me.Controls
    If (c.GetType Is GetType(TextBox)) And ((c.Name <> "txtID") Or (c.Name <> "txtAltEmail")) Then
        'do something
    End If
Next

this works:

For Each c As Control In Me.Controls
    If (c.GetType Is GetType(TextBox)) And (c.Name <> "txtID") Then
        'do something
    End If
Next

thanks, I'm a .net newbie!

dan
  • 505
  • 1
  • 8
  • 26

2 Answers2

2

By the way, you can use LINQ which improves the intelligibility.:

Dim allTextBoxes = From txt In Me.Controls.OfType(Of TextBox)()
                  Where txt.Name <> "txtID" AndAlso txt.Name <> "txtAltEmail"
For Each txt In allTextBoxes
    ' do something with the TextBox '
Next
  • OfType returns only the controls of the given type, in this case TextBoxes
  • Where filters the controls by the Name property (note: And and AndAlso difference)
  • the For Each iterates the resulting IEnumerable(Of TextBox)
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Your first statement does not make sense from a mathematical point of view. The expression

X <> A or X <> B

will always return true (given that A <> B, which is satisfied in your case since "txtID" <> "txtAltEmail").

(If X = A, the second clause will be true. If X = B, the first clause will be true. If X is anything else, both clauses will be true.)

What you probably meant to write was

If (TypeOf c Is TextBox) AndAlso (c.Name <> "txtID") AndAlso (c.Name <> "txtAltEmail") Then

or

If (TypeOf c Is TextBox) AndAlso Not ((c.Name = "txtID") OrElse (c.Name = "txtAltEmail")) Then

which is logically equivalent.

(I've also taken the liberty to change your type check to a more elegant variant and replace And/Or with their more efficient counterparts.)

Heinzi
  • 167,459
  • 57
  • 363
  • 519