VB Validation keeps looping - vb.net

i have been assigned to write a program which saves data about films.We are required to use windows forms in vb.Im trying to validate the data entry for the text box.The text entered must be numbers and must be 4 characters long.The problem im trying to solve is that once it has looked at the value i want the program to allow the user to re-enter a value into the text box but instead it keeps looking at the text box with nothing in then says that it is not in the correct format , without letting the user enter a correct value.here is the code , just for the validation so far:
Dim PassValidate As Boolean = False
ReadFilmData()
NOFilms = NOFilms + 1
ReDim Preserve Film(NOFilms)
'Validate before it is saved to the file'
Do
If IsNumeric(Me.txtFilmID.Text) = True Then
If Me.txtFilmID.TextLength = 0 Then
'Presence check'
MsgBox("You are required to provide a value for the film ID")
ElseIf Me.txtFilmID.TextLength > 4 Then
'Length Check'
MsgBox("The film ID must be 4 numbers long")
ElseIf Me.txtFilmID.TextLength = 4 Then
PassValidate = True
End If
End If
If IsNumeric(Me.txtFilmID.Text) = False Then
MsgBox("The film ID must be a set of numbers ")
End If
If PassValidate = False Then
txtFilmID.Text = ""
MsgBox("Re-enter the value for Film ID")
Call SaveFilmData()
End If
If PassValidate = True Then
Film(NOFilms).FilmID = txtFilmID.Text
End If
Loop Until PassValidate = True

you should check out the validation events in WinForms. They are there to avoid the very problem you are describing.
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

Try removing the Do Loop, there does not seem to be a need for the loop.

Related

Why is Visual Basics Console.ReadLine Buggy and can I fix it?

Hey question about a visual basics program, I am using Console.ReadLine into a string but it seems when I get to that part of the program or any part of my console program the keyboard enter key enters twice or something it completly skips a ReadLine and recieves the input.length 0 before I even have a chance to enter a string.
This isnt runable without my full code I dont think but I cant seem to get ReadLine to prompt for a string when it is initially run, it always returns 0 once and then loops normally. Im wondering if that has something to do with my keyboard or keyboard settings for a visual basics program or command line.
I dont think its a keyboard error because when I am entering code into visual basics it works fine and doesnt send two returns. I couldnt get the full code in code blocks.
...
Shared Sub Main()
Dim s As New Space()
Dim Ship As New Ships()
Dim Run As Boolean = True
Dim ChooseName As Boolean = True
Dim ch As Char
Dim PlayerName As String
While Run = True
s.PrintWelcome()
ch = Convert.ToChar(Console.Read())
If ch = "1" Then
While ChooseName = True
Console.WriteLine("Choose a Name Less then 50 Characters: ")
PlayerName = Console.ReadLine()
If PlayerName.Length > 50 Then
Console.WriteLine("Name is to Long!")
ElseIf PlayerName = "Q" Then
Run = False
Exit While
ElseIf PlayerName.Length <= 0 Then
Console.WriteLine("Please Enter a Player name or Q by itself to quit.")
Else
ChooseName = False
Console.WriteLine("PlayerName: " & PlayerName & " PlayerName.Length: {0}", PlayerName.Length)
End If
End While
If Run = True Then
End If
ElseIf ch = "2" Then
ElseIf ch = "3" Then
Run = False
ElseIf ch = "Q" Then
Run = False
Else
s.PrintWelcome()
End If
End While
End Sub
...
I suspect that you really ought to be structuring your code more like this:
Module Module1
Sub Main()
Do
Console.Write("Please select a menu item from 1, 2, 3 or Q to quit: ")
Dim menuSelection = Console.ReadKey()
Dim input As String = Nothing
Console.WriteLine()
Select Case menuSelection.KeyChar
Case "1"c
Console.WriteLine("What did you want to say about 1?")
input = Console.ReadLine()
Case "2"c
Console.WriteLine("What did you want to say about 2?")
input = Console.ReadLine()
Case "3"c
Console.WriteLine("What did you want to say about 3?")
input = Console.ReadLine()
Case "q"c, "Q"c
Exit Do
Case Else
'Do nothing before repeating the prompt.
End Select
If Not String.IsNullOrEmpty(input) Then
Console.WriteLine("You said: " & input)
End If
Loop
End Sub
End Module
The ReadKey call will immediately read the first key entered by the user. Rather than requiring the user to hit Enter after that key, the application writes the line break itself. It then tests the chararacter represented by that key to see if it is a valid menu item. If it is, it does whatever is appropriate for that item, whether that be reading a line of input or quitting. If the key does not represent a valid menu item then it simply loops back to the prompt. Note also that the Char value entered by the user is actually compared to Char literals, the way it should be done, rather than String literals.

Take list box selection, add value to other list box without allowing duplicates

I have two list boxes on a form I am making. The first list box is linked to a table with various company names. The goal I am after is after double clicking a companies name, the value is inserted in the second list box.
It worked fine until I tried to add code to prevent duplicates from appearing in the second list box, so you couldn't accidentally insert the same company twice. I have tried several different iterations, but with no luck. Anyone able to help with this one? My end goal would be for a msgbox to pop up alerting the user that duplicates are not allowed.
Private Sub ContractorLstbx_DblClick(Cancel As Integer)
Dim found As Boolean
found = False
Dim ID As Long
Dim Contractor As String
For Each newItem In Me.ContractorLstbx.ItemsSelected
For j = 0 To Me.SelectedContractorLst.ListCount - 1
If (Me!ContractorLstbx.ItemData(newItem).Column(1) = Me.SelectedContractorLst.ItemData(j).Column(1)) Then
found = True
Exit For
End If
Next j
If found = False Then
ID = Me.ContractorLstbx.ItemData(newItem)
Me.SelectedContractorLst.AddItem ContractorLstbx!.ItemData(newItem).Column(0) & ";" & Me!ContractorLstbx.ItemData(newItem).Column(1)
End If
found = False
Next newItem
End Sub
This is the full code for your solution. I tried it on test sample and working fine. just copy and paste the code. If you need your comparison to be case sensitive (I mean A <> a) then use Option Compare Binary as in my code below. If it is required to be case insensitive (A = a) just leave the default Option Compare Database or better force it using Option Compare Text
Option Compare Binary
Private Sub ContractorLstbx_DblClick(Cancel As Integer)
Dim found As Boolean
found = False
Dim ID As Long
Dim Contractor As String
For i = 0 To Me.ContractorLstbx.ItemsSelected.Count - 1
For j = 0 To Me.SelectedContractorLst.ListCount - 1
If (Me.ContractorLstbx.Column(1, Me.ContractorLstbx.ItemsSelected(i)) = Me.SelectedContractorLst.Column(1, j)) Then
found = True
Exit For
End If
Next j
If found = False Then
ID = Me.ContractorLstbx.ItemData(Me.ContractorLstbx.ItemsSelected(i))
Me.SelectedContractorLst.AddItem (ContractorLstbx.Column(0, Me.ContractorLstbx.ItemsSelected(i)) & ";" & Me.ContractorLstbx.Column(1, Me.ContractorLstbx.ItemsSelected(i)))
End If
found = False
Next i
End Sub

Storing string then displaying it with a label box

I am trying to store the string from an input box and then display it with dashes in the lblbox for a hangman game for a class.
These are the tasks that I am struggling with:
edit the program to allow a Secret Word of any length.
the program will allow the ‘guesser’ to guess 2 times the length of the word. As an example, the word ‘code’ will allow 8 total guesses.
As the user guesses at letters contained in the word the program will:
Count the number of attempts the user has completed.
Replace the appropriate dash (-) with the correct letter, if the correct letter has been guessed.
When all the letters have been guessed correctly all the dashes (-) should be replaced with the appropriate letters, and a message box should appear stating “Great Job playing Hangman.!”
If the user is unable to guess the correct word in the amount of guesses allowed; the dashes (-) should be replaced with GAME OVER! and a message box should appear stating “Sorry the correct word was________”
2 bonus points will be awarded for displaying all incorrect letters guess in a 3rd label control.
4 more additional bonus points will be awarded for not allowing, or counting a user who guesses the same incorrect letter twice.
Here is my code:
Dim strSecretWord As String
Dim strLetterGuessed As String
Dim blnDashReplaced As Boolean
Dim intNumberOfRemainingGuesses As Integer = 10
Dim intNumofGuesses As Integer = 0
lblSecretWord.Text = ""
lblNumberOfAttempts.Text = ""
'start game and have 1st user input a 5 letter word that 2nd player needs to guess
strSecretWord = InputBox("Please input a 5 letter word for user to guess:", "Please input secret word.").ToUpper
'displays five dashes for the secret word
lblSecretWord.Text = lblSecretWord.Text & "-----"
'guessing player recieves inputbox to make letter guesses
MessageBox.Show("The length of the word is 5 letters, you will be given 10 guesses", "10 guesses", MessageBoxButtons.OK)
MessageBox.Show("Player who gets to guess, BE READY!", "Good Luck Guessing", MessageBoxButtons.OK)
'Counts number of attempts player gets (10) and replaces dashes with guessed letter if correct
'If guessed letter was incorrect, user loses a turn
For intNumberofGuesses = 1 To 10
strLetterGuessed = InputBox("Please guess a letter:", "Letter Guess").ToUpper
'Uses an IntIndex counter of 0 to 4 to execute 5 times (5 dashes)
'Also uses the value of intIndex to check each of the 5 locations of the strSecretWord
For intIndex As Integer = 0 To 4
'if the user has guessed a correct letter then remove a dash and insert the correct letter guessed
If strSecretWord.Substring(intIndex, 1) = strLetterGuessed Then
lblSecretWord.Text = lblSecretWord.Text.Remove(intIndex, 1)
lblSecretWord.Text = lblSecretWord.Text.Insert(intIndex, strLetterGuessed)
blnDashReplaced = True
End If
Next intIndex
'If the user guessed a correct letter on their last guess the blnDashReplaced is set and the true condition of the If statement is executed
If blnDashReplaced = True Then
'if there are no more dashes, and the game has been solved.
If lblSecretWord.Text.Contains("-") = False Then
MessageBox.Show("Great Job playign Hangman!", "Game Over", MessageBoxButtons.OK)
lblRemainingNumberOfAttempts.Text = ""
lblNumberOfAttempts.Text = ""
Exit Sub
Else
blnDashReplaced = False
End If
Else
End If
lblNumberOfAttempts.Text = intNumberofGuesses
intNumberOfRemainingGuesses = intNumberOfRemainingGuesses - 1
lblRemainingNumberOfAttempts.Text = intNumberOfRemainingGuesses
Next
lblSecretWord.Text = "GAME OVER!"
MessageBox.Show("Better luck next time. Sorry the correct word was " & strSecretWord & ".", "You Lost", MessageBoxButtons.OK)
lblRemainingNumberOfAttempts.Text = ""
lblNumberOfAttempts.Text = ""
I added a list box to keep the guessed letters. Other comments and explanations in line.
Public Class Form3
'Move this to a class level variable so it can be seen by
'all the methods in the class
Private strSecretWord As String
Private Sub btnStartGame_Click(sender As Object, e As EventArgs) Handles btnStartGame.Click
Dim strLetterGuessed As String
Dim blnDashReplaced As Boolean
Dim intNumberOfRemainingGuesses As Integer
Dim intNumofGuesses As Integer = 0
'Display correct number of dashes
Dim numberOfDashes As Integer = strSecretWord.Length
'Create a string with correct number of dashes
'This uses and overload of the String constructor that takes a Char and an integer
'as arguments and returns a string with that character repeated that number
'of times. The lower case c following "-" indicates that - is a Char.
Dim TotalNumofGuesses = numberOfDashes * 2
lblRemainingNumberOfAttempts.Text = TotalNumofGuesses.ToString
intNumberOfRemainingGuesses = TotalNumofGuesses
Dim dashString As String = New String("-"c, numberOfDashes)
'displays the dashes
lblSecretWord.Text = dashString
'guessing player recieves inputbox to make letter guesses
'You can use an Interpolated string to display variables in line surrounded by { }.
'In older versions of VB String.Format() will yield the same result.
MessageBox.Show($"The length of the word is {numberOfDashes} letters, you will be given {TotalNumofGuesses} guesses", $"{TotalNumofGuesses} guesses", MessageBoxButtons.OK)
MessageBox.Show("Player who gets to guess, BE READY!", "Good Luck Guessing", MessageBoxButtons.OK)
'Counts number of attempts player gets and replaces dashes with guessed letter if correct
'If guessed letter was incorrect, user loses a turn
For counter = 1 To TotalNumofGuesses
strLetterGuessed = InputBox("Please guess a letter:", "Letter Guess").ToUpper
'If lstLettersGuessed.Contains(strLetterGuessed) Then
If lbxLettersGuessed.Items.Contains(strLetterGuessed) Then
MessageBox.Show($"{strLetterGuessed} has already been guessed.", "Try Again")
'need to do this so they are not cheated out of a guess
TotalNumofGuesses += 1
Continue For 'Moves to the next iteration of the For
End If
lbxLettersGuessed.Items.Add(strLetterGuessed)
'lstLettersGuessed.Add(strLetterGuessed)
'Uses an IntIndex counter of 0 to 4 to execute 5 times (5 dashes)
'Also uses the value of intIndex to check each of the 5 locations of the strSecretWord
For intIndex As Integer = 0 To numberOfDashes - 1
'if the user has guessed a correct letter then remove a dash and insert the correct letter guessed
If strSecretWord.Substring(intIndex, 1) = strLetterGuessed Then
lblSecretWord.Text = lblSecretWord.Text.Remove(intIndex, 1)
lblSecretWord.Text = lblSecretWord.Text.Insert(intIndex, strLetterGuessed)
blnDashReplaced = True
End If
Next intIndex
'If the user guessed a correct letter on their last guess the blnDashReplaced is set and the true condition of the If statement is executed
If blnDashReplaced = True Then
'if there are no more dashes, and the game has been solved.
If lblSecretWord.Text.Contains("-") = False Then
MessageBox.Show("Great Job playing Hangman!", "Game Over", MessageBoxButtons.OK)
'Do this at start of game, player wants to see final score
'lblRemainingNumberOfAttempts.Text = ""
'lblNumberOfAttempts.Text = ""
Exit Sub
Else
blnDashReplaced = False
End If
End If
'This is a shorter way of incrementing a variable
intNumofGuesses += 1
'Can't put an integer into a Text property, it needs a string
lblNumberOfAttempts.Text = intNumofGuesses.ToString
'This is a shorter way of decrementing a variable
intNumberOfRemainingGuesses -= 1
'Can't put an integer into a Text property, it needs a string
lblRemainingNumberOfAttempts.Text = intNumberOfRemainingGuesses.ToString
Next
lblSecretWord.Text = "GAME OVER!"
MessageBox.Show("Better luck next time. Sorry the correct word was " & strSecretWord & ".", "You Lost", MessageBoxButtons.OK)
'Do this at start of game
'lblRemainingNumberOfAttempts.Text = ""
'lblNumberOfAttempts.Text = ""
End Sub
Private Sub btnSetUp_Click(sender As Object, e As EventArgs) Handles btnSetUp.Click
lblSecretWord.Text = ""
lblNumberOfAttempts.Text = "0"
lblRemainingNumberOfAttempts.Text = "0"
lbxLettersGuessed.Items.Clear()
'start game and have 1st user input a 5 letter word that 2nd player needs to guess
strSecretWord = InputBox("Please input a word for user to guess:", "Please input secret word.").ToUpper
End Sub
End Class

Why isn't my VB if statement working?

I'm working on my first project for my visual basic programming class.
I am trying to have this condition statement say if the discount rate is .1 or (10%), then add to the count of customers who got the discount (msngFrequentFlyers) and add to the accumulator that keeps track of total discounts given (msngTotalDiscounts).
I'm very new to all this- please help! Project is due tonight.
Here's my code:
Public Class frmTaxiConsole
'Modular Variable Declaration Section
'Declares msngDiscountRate and sets inital value to -1 for testing user input
Dim msngDiscountRate As Single = -1
'Declares all counter variables
Dim msngNumberOfRides As Single
Dim msngNumberOfFrequentFlyers As Single
'Declares all accumulator variables
Dim msngRevenue As Single
Dim msngTotalDiscounts As Single
Dim msngBillableMiles As Single
If the radio button for the discount is checked:
Private Sub radFrequentFlyer_CheckedChanged(sender As Object, e As EventArgs) Handles radFrequentFlyer.CheckedChanged
msngDiscountRate = 0.1 'Sets discount rate to 10% upon selection of radio button
End Sub
This is the if statement that's not working, in the "Process Transaction" click event:
If msngDiscountRate = "0.1" Then 'Checks to see if this transaction had any discount
msngNumberOfFrequentFlyers += 1 'If so, adds 1 to the number of discounts given
msngTotalDiscounts = msngTotalDiscounts + (sngSubTotal * msngDiscountRate) 'Also adds the discount amount to the total discounts accumulator (without making it negative)
End If
Here's the entire code for the "Process Transaction" click event:
Private Sub btnProcessTx_Click(sender As Object, e As EventArgs) Handles btnProcessTx.Click
'Local Variable Declaration Section
Dim sngMilesDriven As Single
Dim dblOdometerStart As Double
Dim dblOdometerEnd As Double
Dim sngInitialFee As Single
Dim sngPerMileFee As Single
Dim sngMileageCharge As Single
Dim sngSubTotal As Single
Dim sngDiscount As Single
Dim sngTotalDue As Single
'Data Input + Testing Section
'Changes all text box backcolors white, in case they had been turned red due to an error
txtOdometerStart.BackColor = Color.White
txtOdometerEnd.BackColor = Color.White
txtInitialFee.BackColor = Color.White
txtPerMileFee.BackColor = Color.White
'Try/Catch validates user input for Inital Fee
Try
'Attempts to convert user input to Single and store as a local variable
sngInitialFee = CSng(txtInitialFee.Text)
Catch ex As Exception
'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
MessageBox.Show("Please enter a valid initial fee.", "Invalid Initial Fee", MessageBoxButtons.OK)
txtInitialFee.BackColor = Color.Red
txtInitialFee.Focus() 'Focuses in text box where error occured so user can fix
Exit Sub
End Try
'Try/Catch validates user input for Per-Mile Fee
Try
'Attempts to convert user input to Single and store as a local variable
sngPerMileFee = CSng(txtPerMileFee.Text)
Catch ex As Exception
'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
MessageBox.Show("Please enter a valid per-mile fee.", "Invalid Per-Mile Fee", MessageBoxButtons.OK)
txtPerMileFee.BackColor = Color.Red
txtPerMileFee.Focus() 'Focuses in text box where error occured so user can fix
Exit Sub
End Try
'Try/Catch validates user input for starting milage
Try
'Attempts to convert user input to Double and store as a local variable
dblOdometerStart = CDbl(txtOdometerStart.Text)
Catch ex As Exception
'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
MessageBox.Show("Please enter a valid starting milage.", "Invalid Odometer Reading", MessageBoxButtons.OK)
txtOdometerStart.BackColor = Color.Red
txtOdometerStart.Focus() 'Focuses in text box where error occured so user can fix
Exit Sub
End Try
'Try/Catch validates user input for ending milage
Try
'Attempts to convert user input to Double and store as a local variable
dblOdometerEnd = CDbl(txtOdometerEnd.Text)
Catch ex As Exception
'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
MessageBox.Show("Please enter a valid ending milage.", "Invalid Odometer Reading", MessageBoxButtons.OK)
txtOdometerEnd.BackColor = Color.Red
txtOdometerEnd.Focus() 'Focuses in text box where error occured so user can fix
Exit Sub
End Try
'If statement ensures Inital Fee is a positive number
If sngInitialFee < 0 Then
'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
MessageBox.Show("Initial Fee cannot be negative.", "Invalid Inital Fee", MessageBoxButtons.OK)
txtInitialFee.BackColor = Color.Red
txtInitialFee.Focus() 'Focuses in text box where error occured so user can fix
Exit Sub
End If
'If statement ensures Per-Mile Fee is a positive number
If sngPerMileFee < 0 Then
'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
MessageBox.Show("Per-Mile Fee cannot be negative.", "Invalid Per-Mile Fee", MessageBoxButtons.OK)
txtPerMileFee.BackColor = Color.Red
txtPerMileFee.Focus() 'Focuses in text box where error occured so user can fix
Exit Sub
End If
'If statement checks to make sure starting milage is smaller number than ending milage
If dblOdometerEnd <= dblOdometerStart Then
'If ending milage is smaller number than starting milage, displays a messagebox and exits sub.
MessageBox.Show("Your ending mileage cannot be less than or equal to your starting mileage. Please check your odometer readings.", "Invalid Odometer Reading", MessageBoxButtons.OK)
txtOdometerStart.Focus() 'Focuses in starting odometer reading text box so user can fix
Exit Sub
End If
'If statement checks to make sure both odometer readings are positive numbers.
If dblOdometerEnd < 0 Or dblOdometerStart < 0 Then
'If either odometer reading is negative, displays a messagebox and exits sub.
MessageBox.Show("Both your odometer readings must be positive numbers. Please check your odometer readings.", "Invalid Odometer Reading", MessageBoxButtons.OK)
txtOdometerStart.Focus() 'Focuses in starting odometer reading text so user can fix
Exit Sub
End If
'If statement checks to ensure user has seleted one of the two radio buttons
If msngDiscountRate = -1 Then
'If msngDiscountRate is the same as the initial value, neither option has been chosen, an error message is shown, and sub exited.
MessageBox.Show("Please choose a frequent flyer status.", "Frequent Flyer?", MessageBoxButtons.OK)
Exit Sub
End If
'Calculations Section
sngMilesDriven = CSng(dblOdometerEnd - dblOdometerStart) 'Subtracts starting mileage from ending mileage, converts to single, stores as var sngMilesDriven
sngMileageCharge = sngMilesDriven * sngPerMileFee 'Multiplies the miles driven by the per-mile fee and stores as var sngMileageCharge
sngSubTotal = sngMileageCharge + sngInitialFee 'Adds the milage charge to the initial fee, stores as var sngSubTotal
sngDiscount = sngSubTotal * msngDiscountRate * -1 'Multiplies subtotal by discount rate, makes negative, stores as var sngDiscount
sngTotalDue = sngSubTotal + sngDiscount 'Subtracts discounts from subtotal, stores as var sngTotalDue
'Counter and Accumulator Operations
msngNumberOfRides += 1 'Adds 1 to the number of rides given
If msngDiscountRate = "0.1" Then 'Checks to see if this transaction had any discount
MsgBox(msngDiscountRate)
msngNumberOfFrequentFlyers += 1 'If so, adds 1 to the number of discounts given
msngTotalDiscounts = msngTotalDiscounts + (sngSubTotal * msngDiscountRate) 'Also adds the discount amount to the total discounts accumulator (without making it negative)
End If
msngRevenue = msngRevenue + sngTotalDue 'Adds the total due for current transaction to revenue accumulator
msngBillableMiles = msngBillableMiles + sngMilesDriven 'Adds miles from this transaction to running total
'Output Section
'Displays above calculations in respective labels and formats as currency if neccecary.
lblMilesDrivenOutput.Text = sngMilesDriven
lblSumInitialFeeOutput.Text = FormatCurrency(sngInitialFee) 'Formats sngInitialFee as currency and displays in lblSumInitialFeeOutput
lblSumMilageChargeOutput.Text = FormatCurrency(sngMileageCharge)
lblSumSubTotalOutput.Text = FormatCurrency(sngSubTotal)
lblSumDiscountOutput.Text = FormatCurrency(sngDiscount)
lblSumTotalDueOutput.Text = FormatCurrency(sngTotalDue)
'Displays all counter and accumulator variables after they are updated
lblTotalRidesOutput.Text = msngNumberOfRides
lblFrequentFlyersOutput.Text = msngNumberOfFrequentFlyers
lblRevenueOutput.Text = FormatCurrency(msngRevenue)
lblTotalDiscountsOutput.Text = FormatCurrency(msngTotalDiscounts)
lblBillableMilesOutput.Text = msngBillableMiles
End Sub
Firstly as mentioned above you'll need to remove the quotes around the 0.1 in your if statement, this won't work as it's comparing a number to a string.
I'm no expert on floating-point arithmetic, but as Plutonix alludes to, I think the problem when you tried it without quotes is that the 0.1 you're comparing your msngDiscountRate in the if statement defaults to a Double, whereas you've declared your variable as a Single, so the if statement evaluates to false.
You could either declare your msngDiscountRate variable as Double instead, or cast the 0.1 to a Single to get around it. These simple examples might help -
'Variable declared as a Single, compared to 0.1 (a Double) - If statement evaluates to false
Dim msngDiscountRateExample1 As Single = -1
msngDiscountRateExample1 = 0.1
If msngDiscountRateExample1 = 0.1 Then
Debug.Print(msngDiscountRateExample1.ToString)
End If
'Variable declared as a Double, compared to 0.1 (another Double) - If statement evaluates to true
Dim msngDiscountRateExample2 As Double = -1
msngDiscountRateExample2 = 0.1
If msngDiscountRateExample2 = 0.1 Then
Debug.Print(msngDiscountRateExample2.ToString)
End If
'Variable declared as a Single, compared to 0.1 (a Double) which is *cast* as a Single - If statement evaluates to true
Dim msngDiscountRateExample3 As Single = -1
msngDiscountRateExample3 = 0.1
If msngDiscountRateExample3 = CSng(0.1) Then
Debug.Print(msngDiscountRateExample3.ToString)
End If

For loop for bowling score array

I am trying to create a bowling program that will display the scores given in a multi-line text box. I've manage to get the program giving an output, but when it runs it skips asking for new inputs and just gives 5 0s on seperate lines and nothing else. I'm completely lost, any help is very much appreciated
EDIT: Sorry should have changed errors to reflect the programs changes, it looks like this now. It gives 0's instead of using the value I gave it, but it does ask for each input now.
For gameNumber As Integer = 1 To 5 Step 1
lblEnterScore.Text = "Enter Score for game #" & gameNumber
Dim Testint As Integer ' define an Integer for testing
Try
Testint = CInt(txtScoreInput.Text) ' try to convert whatever they entered to Int
Catch
MessageBox.Show("Entry is not an Integer") ' If you are here then the CInt failed for some reason, send a message
txtScoreInput.SelectAll()
txtScoreInput.Focus()
Exit Sub
End Try
If txtScoreInput.Text.Contains(".") Then
MsgBox("Bowling Score must be a whole number.")
txtScoreInput.SelectAll()
txtScoreInput.Focus()
Exit Sub
End If
If txtScoreInput.Text > MAXIMUM_SCORE Or txtScoreInput.Text < MINIMUM_SCORE Then
MsgBox("Bowling Score must be between 1 and 300.")
txtScoreInput.SelectAll()
txtScoreInput.Focus()
Exit Sub
End If
scoreInput(gameNumber) = CInt(txtScoreInput.Text)
' and store it in the array
' and increment the gamecounter for the next time through the loop
Next
'btnEnterScore.Enabled = False
' place the good score into the multi-line textbox
txtScoreOutputs.Text = gameScore & vbCrLf & txtScoreOutputs.Text
End Sub
If it was me, here's what I would do... Just a suggestion; I also cut out over half of your code and stopped it from throwing exceptions as well... You can put this in a click event or where ever you need it as well. You can modify this as well to take as many as you want from user input as well not just limit them from entering score's. Your user also has the option to get out of that loop when they choose to do so as well, not keeping them inside the loop...
Private ScoreLists As New List(Of Integer) 'Hold your inputted values
Private Const MAXIMUM_SCORE As Integer = 300 'Max score
Private Const MINIMUM_SCORE As Integer = 1 'Min score
Private blnStop As Boolean = False
Try
For gameNumber As Integer = 1 To 5
Dim intScore As Integer = 0
Do Until (intScore >= MINIMUM_SCORE And intScore <= MAXIMUM_SCORE) OrElse blnStop
If Not Integer.TryParse(InputBox("Please enter a score for game # " & gameNumber.ToString), intScore) Then
If MsgBox("Bowling Score must be a whole number. Stop getting scores?.", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
blnStop = True
Exit For
End If
End If
Loop
ScoreLists.Add(intScore)
Next
'Display the results...
For i As Integer = 0 To ScoreLists.Count - 1
txtScoreOutputs.Text &= ScoreLists.Item(i.ToString)
Next
ScoreLists.Clear()
Catch ex As Exception
End Try
Construct your logic like this (pseudo):
Loop
{
AskUserForInput()
ProcessUserInput()
}
The loop part will control how many scores the user is prompted to enter. The AskUserForInput() function will prompt the user to type in a new score, and the ProcessUserInput() function will get the value and store it in an array or print it to the screen, etc.
Your current logic is not waiting for any new user input before trying to add to the scores. You are also getting zeros because you're setting the txtScoreOutputs with gameScore, which doesn't look like it's been set to the user's input.