Link to home
Start Free TrialLog in
Avatar of ouch_mybrain_
ouch_mybrain_

asked on

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

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):

User generated image
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.
ASKER CERTIFIED SOLUTION
Avatar of andygrant2005
andygrant2005
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ouch_mybrain_
ouch_mybrain_

ASKER

Excellent, thank you very much. Glad to know I was close.
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