Rado Sabo
Rado Sabo

Reputation: 33

Visual Basic Or, OrElse still returning false

I am new to VB.net and i have little problem with this statement, i want to throw msgBox just if in txtBox txtTitul is not "Bc." or "" or "Ing." ... and this is throwing msgBox everytime

If Not txtTitul.Text.Equals("Bc.") _
    OrElse Not txtTitul.Text.Equals("") _
    OrElse Not txtTitul.Text.Equals("Bc.") _
    OrElse Not txtTitul.Text.Equals("Mgr.") _
    OrElse Not txtTitul.Text.Equals("Ing.") _
    OrElse Not txtTitul.Text.Equals("Mgr. art.") _
    OrElse Not txtTitul.Text.Equals("Ing. arch.") _
    OrElse Not txtTitul.Text.Equals("MUDr.") _
    OrElse Not txtTitul.Text.Equals("MVDr.") _
    OrElse Not txtTitul.Text.Equals("RNDr.") _
    OrElse Not txtTitul.Text.Equals("PharmDr.") _
    OrElse Not txtTitul.Text.Equals("PhDr.") _
    OrElse Not txtTitul.Text.Equals("JUDr.") _
    OrElse Not txtTitul.Text.Equals("PaedDr.") _
    OrElse Not txtTitul.Text.Equals("ThDr.") Then
    MsgBox("Neplatny titul!")
    Exit Sub
End If

Upvotes: 0

Views: 200

Answers (2)

Prisoner
Prisoner

Reputation: 1857

Consider your input is "Bc."

Not txtTitul.Text.Equals("Bc.")  <- false
Not txtTitul.Text.Equals("")     <- true
false OrElse true = true

Consider your input is "abc"

Not txtTitul.Text.Equals("Bc.")  <- true
Not txtTitul.Text.Equals("")     <- true
true OrElse true = true

For solution, you may consider Tim's answer.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460228

You don't want to use OrElse but AndAlso, because only if it's not one of those it's an invalid title (so not 1st and not 2nd and not 3rd and so on....).

But can i show you a much simpler and more maintainable approach?

Dim allowedTitles = {"Bc.","Ing.","Ing. arch.","MUDr.","MVDr.","RNDr.","PhDr.","PaedDr.","ThDr."}
If Not allowedTitles.Contains(txtTitul.Text) Then 
    MsgBox("Invalid title!")
End If

If you also want to accept lower-case, so ignore the case, you can use:

If Not allowedTitles.Contains(txtTitul.Text, StringComparer.InvariantCultureIgnoreCase) Then 
    MsgBox("Invalid title!")
End If

Upvotes: 6

Related Questions