VB.NET beginner question regarding an array - sample code/error provided >_<

ouch_mybrain_
ouch_mybrain_ used Ask the Experts™
on
Hello Experts,

I am a beginner who is trying to learn vb.net. I need some help in understanding why I am getting an error when trying to check if a variable exists against an array (see below):

Error
Here is my code ... also please note that on my form I have a button called "Button1" and a text box called "txtBoxGuess". The idea is that I enter a character into the textbox and then press the button. If the character exists in the string then I get a message saying "hooray!", and if it is not in the array, "boo".

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGuess.Click

        Dim sport(6) As String
        sport(0) = "c"
        sport(1) = "r"
        sport(2) = "i"
        sport(3) = "c"
        sport(4) = "k"
        sport(5) = "e"
        sport(6) = "t"

        Dim Guess As String
        Guess = txtBoxGuess.Text

        If sport.Contains = Guess Then
            MsgBox("Hooray!")
        Else
            MsgBox("Boo1")
        End If
    End Sub
End Class

Open in new window


Thanks.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hi there,

Your so close.  Its just the syntax that's a little out.

Try the following :

        If sport.Contains( Guess ) Then
            MsgBox("Hooray!")
        Else
            MsgBox("Boo1")
        End If

This should do the trick as Contains is a method.

Another thing worth noting, is when comparing user input, its often a good idea to convert the variable to lower or upper case before the comparison, as "A" won't match "a"

Author

Commented:
Excellent, thank you very much. Glad to know I was close.
Top Expert 2015

Commented:
I do not see however why you use an array of strings to store characters.

Either use a single String:

    Dim Sport As String = "cricket"

Or use an array of characters:

    Dim sport(6) As Char
        sport(0) = "c"c
        sport(1) = "r"c
        sport(2) = "i"c
        sport(3) = "c"c
        sport(4) = "k"c
        sport(5) = "e"c
        sport(6) = "t"c

The array could also be initialized the following way:

    Dim sport() As Char = "cricket".ToCharArray

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial