Avatar of FalconTwo
FalconTwo

asked on 

VB.NET Question

Working on another assignment and ran into a snag. I am writing the code and testing each routine. When I compile and test and I unable to close the error window

What am I doing wrong

Option Strict On 'Enforces strict data typing
Public Class frmHockeyStats
    Dim strName As String
    Dim intSeason, intGoals, intAssist As Integer

    Private Sub btnGetStats_Click(ByVal sender As Object, _
                                  ByVal e As System.EventArgs) _
                              Handles btnGetStats.Click

        'Accept and Validate Name box is not empty
        Do While True
            ' strName = Me.txtName.Text
            If String.IsNullOrEmpty(strName) = True Then
                MessageBox.Show("Name must be provided", "Error", _
                            MessageBoxButtons.OK, MessageBoxIcon.Error)
            Else
                Exit Do
            End If
        Loop

        'Accept and Validate Season
        Do While True
            If Integer.TryParse(Me.txtSeasons.Text, intSeason) = False Then
                MessageBox.Show("Season Must be a Number", "Error", _
                                MessageBoxButtons.OK, MessageBoxIcon.Error)
                Me.txtSeasons.Focus()
                Me.txtSeasons.SelectAll()
            Else

            End If
            If intSeason > 0 AndAlso intSeason <= 20 Then
                btnGetStats.Enabled = True
            Else
                Exit Do
            End If
        Loop
    End Sub

    '------------------------------------------------------------------------
    'btnExit Click Event Procedure.
    '1. Closes the form.
    '
    'Parameters:
    ' Standard (IDE-supplied)
    '
    'Calling procedure (example):
    ' When user clicks on "Exit" button (btnExit)
    '------------------------------------------------------------------------

    Private Sub btnExit_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnExit.Click
        Me.Close()
    End Sub

    'btnClear Click Event Procedure.
    ' When the Clear button is selected, the values are cleared
    Private Sub btnClear_Click(ByVal sender As System.Object, _
                               ByVal e As System.EventArgs) _
                                Handles btnClear.Click
        txtName.Text = ""
        txtSeasons.Text = ""
        txtGoals.Text = ""
        txtAssist.Text = ""
        lstSeason.Items.Clear()
    End Sub
End Class
Visual Basic.NET

Avatar of undefined
Last Comment
kaufmed
Avatar of kaufmed
kaufmed
Flag of United States of America image

Here:

Do While True
    ' strName = Me.txtName.Text
    If String.IsNullOrEmpty(strName) = True Then
        MessageBox.Show("Name must be provided", "Error", _
                    MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
        Exit Do
    End If
Loop

Open in new window


You have an infinite loop because your condition is hard-coded to True. This is not tragic considering you have an Exit Do in the Else clause. However, think about this:  If the Else clause is never entered (which means the If clause was entered), how can you ever break out of the loop based on your current code?
Avatar of Ken Butters
Ken Butters
Flag of United States of America image

Just a tip:

To track down this sort of error yourself, I would highly recommend going through the code step by step in trace.  

That will show you exactly where the logic flaws are.

Liberal use of breakpoints and careful stepping will usually uncover most mistakes.
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Just to add to Kaufmed, you have another infinite while loop on the seasons field.

The way I usually handle this sort of logic is as below

ButtonClick:

If String.IsNullOrEmpty(txtName.Text.Trim) Then
    messagebox.show "Error"
    txtName.Focus
    Exit Sub
End If
...
Avatar of adriankohws
adriankohws
Flag of Singapore image

Yes, I agreed with CodeCruiser, I usually don't loop on such validations, when you identify one, focus the control and prompt the user, end the routine, that's all.

For numerical controls, I usually don't even check on validation on windows app. You can use keypress of the textbox to identify if it's numeric, otherwise, stop the keypress, following is one that only allows numbers and decimals.

Private Sub numeric_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtPrice.KeyPress, txtWeight.KeyPress, txtVolWeight.KeyPress, txtRPrice.KeyPress, txtItemPrice.KeyPress
        Dim obj As TextBox = sender
        Dim KeyAscii As Integer = Asc(e.KeyChar)
        e.Handled = RestrictTxt(KeyAscii, obj.Text)
    End Sub

 Public Function RestrictTxt(ByVal keyz As Integer, ByVal eString As String) As Boolean
        'This function allows all numeric keys and decimal point
        If (keyz >= 48 And keyz <= 57) Or keyz = 46 Or keyz = 127 Or keyz = 8 Then
            RestrictTxt = InStr(1, eString, "..") > 0 'Check to see if there are consecutive dots
        Else
            RestrictTxt = True
        End If
    End Function
Avatar of FalconTwo
FalconTwo

ASKER

Guys I am a student and I am now learning VB.NET so go easy with me LOL

Thanks for your input. I have tried several combination going with what I see the professor did in class. Not sure why hos work and mine isn't

Brian W.
Avatar of kaufmed
kaufmed
Flag of United States of America image

If you take time to understand what I mentioned to you above, you should see why the code repeats the prompt without breaking out of the loop. You can post your updated code to show what you are trying and we can discuss where you might be going wrong.
Avatar of FalconTwo
FalconTwo

ASKER

Its a program that will calculate and display the career statistics for a hockey player. The program will input the name of the hockey player (the name must be a non-empty string) and the number of seasons played, which must be at least one season and no more than 20 seasons. Processing the goals and assists cannot start until a valid season value is provided. Once the valid season value is provided, the program will prompt the user to provide the number of goals and assists for each season. The valid number of goals is between 0 and 60 and the valid number of assists is between 0 and 60. The program will keep a running total of the number of goals, the number of assists, and the total points. Also, a list of the each season’s data will be display after the season data is provided. Once all the season data are collected, the program shall list the summary information for the player and all the seasons

I am going thru it but somehow its still crashing

This is pretty much what I have done so far
Option Strict On 'Enforces strict data typing
Public Class frmHockeyStats
    Dim strName As String
    Dim intSeason, intGoals, intAssist As Integer

    Private Sub btnGetStats_Click(ByVal sender As Object, _
                                  ByVal e As System.EventArgs) _
                              Handles btnGetStats.Click

        'Accept and Validate Name box is not empty
        Do While True
            strName = Me.txtName.Text
            If String.IsNullOrEmpty(strName) = True Then
                MessageBox.Show("Name must be provided", "Error", _
                            MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
                Exit Do
            End If

        Loop

        'Accept and Validate Season
        Do While True
            If Integer.TryParse(Me.txtSeasons.Text, intSeason) = False Then
                MessageBox.Show("Season Must be a Number", "Error", _
                                MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If
            If intSeason < 0 Or intSeason > 20 Then
                MessageBox.Show("Season must be between 1 and 20 - Try again", "Error", _
                                MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
                Exit Do
            End If

        Loop
    End Sub

    '------------------------------------------------------------------------
    'btnExit Click Event Procedure.
    '1. Closes the form.
    '
    'Parameters:
    ' Standard (IDE-supplied)
    '
    'Calling procedure (example):
    ' When user clicks on "Exit" button (btnExit)
    '------------------------------------------------------------------------

    Private Sub btnExit_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnExit.Click
        Me.Close()
    End Sub

    'btnClear Click Event Procedure.
    ' When the Clear button is selected, the values are cleared
    Private Sub btnClear_Click(ByVal sender As System.Object, _
                               ByVal e As System.EventArgs) _
                                Handles btnClear.Click
        txtName.Text = ""
        txtSeasons.Text = ""
        txtGoals.Text = ""
        txtAssist.Text = ""
        lstSeason.Items.Clear()
    End Sub


End Class
Avatar of kaufmed
kaufmed
Flag of United States of America image

One thing to point out, and I believe others already mentioned something similar, is that you have a WinForms project. There isn't any real benefit to having a loop that checks the input of a TextBox and prompts the user of incorrect input. If you loop, there's no way for the user to actually modify the input until the loop ends. You are ending the loop, but I suggest not even having a loop to begin with. There is no tangible benefit to having it. In my opinion, you are actually hurting the readability/understandability of your code. A simple If check on the condition should suffice.

My suggestion would be to start with cleaning up your loops and making them into something more sensible (i.e. If blocks). It's often easier to start with some small piece of functionality, test it until it works, and then add on to that functionality (without touching what you've already tested).
Avatar of adriankohws
adriankohws
Flag of Singapore image

When will ever your below test be "False" if user enters something into
txtName which is supposed to be? So if user enters something, it went into infinite loop.

As mentioned, don't loop, pointless and moreover, with  your ambiguous condition....

  'Accept and Validate Name box is not empty
        Do While True
            strName = Me.txtName.Text
            If String.IsNullOrEmpty(strName) = True Then
                MessageBox.Show("Name must be provided", "Error", _
                            MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
                Exit Do
            End If
        Loop

Actually, you won't have a case where it will become false, be it someone enters the textbox or not, so what are you trying to do? And your following codes I didn't really go through but at one look seems to be always hit exit loop in all conditions, so what's the loop for?
ASKER CERTIFIED SOLUTION
Avatar of adriankohws
adriankohws
Flag of Singapore image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of kaufmed
kaufmed
Flag of United States of America image

An interesting choice of answer selection.

You might consider spending some time reading up on beginner's topics since the information given you here appears to have been too much for you to digest. Good luck to you in your coding endeavors.
Visual Basic.NET
Visual Basic.NET

Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to Visual Basic pre-2002, it is not the same technology,

96K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo