Question How can I get this to work?

audio_uphoria

Active member
Joined
Jan 28, 2009
Messages
31
Programming Experience
Beginner
Spent a lot of time typing this, dont know how to convert the string to boolean, please help. Thanks. btw option strict is on

VB.NET:
Dim state As String
        state = txtState.Text

        If state <> "AL" Or "AK" Or "AZ" Or "AR" Or "CA" Or "CO" Or "CT" Or "DE" Or "DC" Or "FL" Or "GA" _
        Or "HI" Or "ID" Or "IL" Or "IN" Or "IA" Or "KS" Or "KY" Or "LA" Or "Me" Or "MD" Or "MA" Or "MI" Or "MN" Or "MS" _
        Or "MO" Or "MT" Or "NE" Or "NV" Or "NH" Or "NJ" Or "NM" Or "NY" Or "NC" Or "ND" Or "OH" Or "OK" Or "OR" Or "PA" _
        Or "RI" Or "SC" Or "SD" Or "TN" Or "TX" Or "UT" Or "VT" Or "VA" Or "WA" Or "WV" Or "WI" Or "WY" Then
            MessageBox.Show("Please enter a valid state abbreviation")
            txtState.Focus()

        End If
 
Last edited:
Here's a better approach:
VB.NET:
Dim States As New List(Of String)
States.AddRange(New String() {"AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "Me", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"})
If States.Contains(txtState.Text.Trim.ToUpper) = False Then
    Messagebox.Show("Please enter a valid state abbreviation")
    txtState.Focus()
End If
I would also declare the list at the class (form) level instead of re-declaring it in that sub
 
Just so you know, to do it the way you were originally trying it should have been:
VB.NET:
If state <> "AL" AndAlso state <> "AK" AndAlso state <> "AZ" ...
Another option would have been a Select Case statement:
VB.NET:
Select Case state
    Case "AL", "AK", "AZ", ...
        'OK
    Case Else
        'Not OK
End Select
That said, if all they can enter is a state abbreviation then why give them the freedom to enter anything else? Why not use a ComboBox and enter the state abbreviations yourself? That way you ensure valid input with no code.
 
You bring up a good point about the combo box. This is for an assignment in a class and we havn't covered combo boxes yet so I don't know if we can use it or not.
 
Back
Top