hi everybody, im doing a project in vb 2010 its a simple "guess the number between 1 and 30"
i have it all finished working properly , my only remaining issue is, if i enter a character or letter into the combobox, it crashes the system. i got a piece of code to counter the issue but its message box appears everytime i press enter. its running in sync with the game instead of only when an invalid entry occurs.


 Private Sub btnEnter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnter.Click   'enter pressed

        If Not IsNumeric(cboRange.Text) Then cboRange.Text = "0"
        MsgBox("You Have Entered Invalid Characters, Please Try Again")
        cboRange.Focus()

        (above is the code than stops wrong input,by right the next line should be "else" but it wont accept it)


        num = cboRange.Text 'num reassigned to value of cboRange box
        lblX.Text = X
        lblInstructions.Text = ""   'clear instructions
        lblInstructions2.Text = ""   'clear instructions
        txtAttempts.Text = Val(txtAttempts.Text) + 1    'update attempt counter +1 everytime




        If num = X Then 'if num equals X
            txtHint.Text = "YOU WIN!!!!"    'output message in textbox
            MsgBox("Congratulations!!!")    'display output on message box
            Me.BackgroundImage = ImageList1.Images(8)   'display background image
            msg = "  do you want to Exit"   'messagebox for instructions
            title = "MsgBox Close"  'option box

            style = MsgBoxStyle.Critical Or MsgBoxStyle.YesNoCancel 'options displayed
            response = MsgBox(msg, style, title)    'responses in order 

            If response = MsgBoxResult.Yes Then 'user choose yes
                'perform some action
                Me.BackgroundImage = ImageList1.Images(14)  'Show background image
                MsgBox("You have played " & txtGamesPlayed.Text & " games")    'show statistics
                MsgBox("Your Average Guess Total is " & txtAttempts.Text / txtGamesPlayed.Text) 'show statistics
                MsgBox("THANK YOU FOR PLAYING THE GUESSING GAME!!") 'display output in textbox

                End 'close the programme
            ElseIf MsgBoxResult.No Then 'user choose no

                txtGamesPlayed.Text = Val(txtGamesPlayed.Text) + 1  'update games counter +1
                txtAverage.Text = "Your Average is " & txtAttempts.Text / txtGamesPlayed.Text   'show statistics
                MsgBox("You have played " & txtGamesPlayed.Text & " games")    'show statistics
                MsgBox("Your Average Guess Total is " & txtAttempts.Text / txtGamesPlayed.Text) 'show statistics

                Randomize() 'generate random number
                X = randomClass.Next(min, max)  'between min & max values
                txtHint.Clear() 'clear textbox
                txtAttempts.Clear() 'clear textbox
                txtAttempts.Text = "0" 'assign 0 to textbox
                lblX.Text = ""
                Me.BackgroundImage = ImageList1.Images(13)  'display image
                cboRange.Text = "0" 'reset range to zero
                Return  'refresh screen

            ElseIf MsgBoxResult.Cancel Then  'user choose cancel
                'perform some action
                txtGamesPlayed.Text = Val(txtGamesPlayed.Text) + 1  'update game counter+1
                txtAverage.Text = "Your Average is " & txtAttempts.Text / txtGamesPlayed.Text   'show statistics
                MsgBox("You have played " & txtGamesPlayed.Text & " games")    'show statistics
                MsgBox("Your Average Guess Total is " & txtAttempts.Text / txtGamesPlayed.Text) 'show statistics
                txtHint.Clear() 'clear textbox
                txtAttempts.Clear() 'clear textbox
                txtAttempts.Text = "0"  'assign 0 to textbox
                Me.BackgroundImage = ImageList1.Images(13)  'display image
                cboRange.Text = "0" 'reset range to zero
                lblX.Text = ""

                Randomize() 'generate random number
                X = randomClass.Next(min, max)  'between min & max values
                Return  'refresh screen
            End If   'end statement
        End If   'end statement

        If num < X Then 'if num less
            txtHint.Text = ("You are too low!!!")   'output message in hint 
            Me.BackgroundImage = ImageList1.Images(12)  'display image

        End If   'end statement
        If num > X Then 'if num greater
            txtHint.Text = ("You are too high!!!")  'output message in hint 
            Me.BackgroundImage = ImageList1.Images(11)  'display image

        End If   'end statement
        If num < min And num > max Then 'for invalid entry
            MsgBox("you have entered a number outside the range, Please try again") 'display message box
        End If   'end statement
        end sub

For numeric input I suggest you use a NumericUpDown control. It will accept only numbers and you can set maximum and minimum values for the control (and alter them at runtime).

You set the messagebox style to Critical or YesNoCancel but only ever check for Yes, No or Cancel. Try setting it up as follows:

Select Case MsgBox(msg, MsgBoxStyle.YesNoCancel, title)

    Case MsgBoxResult.Yes
        .
        .
        .
    Case MsgBoxResult.No
        .
        .
        .
    Case MsgBoxCancel
        .
        .
        .
End Select    

You retest where it is not necessary. Your code basically looks like

If num = x Then
    .
End If

If num < x Then
    .
End If

If num > x Then
    .
End If

If the first case is true then you don't need to do the following two tests. Using the NumericUpDown control with a Select Case gives you

Select Case NumericUpDown1.Value

    Case Is = X
        Me.Text = "you guessed it"

    Case Is < X
        Me.Text = "too low"

    Case Is > X
        Me.Text = "too high"

End Select
commented: True +8

You can simplify this code with something like this:

Public Class Main
    Dim rnd As New Random
    Dim iNumberToGuess As Integer

    Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
        Try
            If IsNumeric(txtAttempt.Text) Then
                If CheckGuess(CInt(txtAttempt.Text)) Then
                    Dim res As DialogResult = MsgBox("Do you want to exit the application?", MsgBoxStyle.YesNo, "Congratulations!")
                    If res = MsgBoxResult.Yes Then
                        'Place your code here.
                    ElseIf res = MsgBoxResult.No Then
                        iNumberToGuess = GetRandom()
                        ClearAll()
                    Else
                        MsgBox("Could not determine result!")
                    End If
                Else
                    txtAttempt.Text = Missed(CInt(txtAttempt.Text))
                End If
            Else
                MsgBox("Only numbers can be entered to guess.")
            End If
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Function CheckGuess(ByVal iGuess As Integer) As Boolean
        If iGuess = iNumberToGuess Then Return True Else Return False
    End Function

    Private Function GetRandom() As Integer
        Return rnd.Next(0, 30)
    End Function

    Private Function Missed(ByVal iInVal As Integer) As String
        If iInVal > iNumberToGuess Then
            Return "You are to high!"
        Else
            Return "You are to low!"
        End If
    End Function

    Private Sub ClearAll()
        'Place clear code here.
    End Sub
End Class

thannks for your help but iwas given guidelines in the project for what i could use. i wasnt allowed use numeric up/down, only comboboxes. i got this code sorted earlier. i had to change my variables to string and it works for all faults. sometimes the simplest things drive you mad. also ii have to be able to change the range during the game to any set of numbers and few other tweaks so i didnt want to change all the code completely. thanks very much guys for taking the time to reply to me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.