Instead of a For Loop and InputBox, add a TextBox to your Form and use that as the input mechanism. Just like in the example from Sebastian, use Integer.TryParse() to parse the TextBox to an Integer each time the Button is pressed (only one number per button click). Once you have seven things in your ListBox, you can disable the Button and the TextBox so that no more inputs can be made (or you can make the Button click tell the user they already have seven inputs):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Static intRunningTotal As Integer = 0
Dim intScore As Integer
If Integer.TryParse(TextBox1.Text, intScore) Then
If intScore >= 0 Then
intRunningTotal = intRunningTotal + intScore
Dim entry As String = (ListBox1.Items.Count + 1).ToString() + vbTab + intScore.ToString() + vbTab + intRunningTotal.ToString()
ListBox1.Items.Add(entry)
If ListBox1.Items.Count = 7 Then
Button1.Enabled = False
TextBox1.Enabled = False
End If
Else
MessageBox.Show("Score must be greater than or equal to zero.")
TextBox1.Focus()
TextBox1.SelectAll()
End If
Else
MessageBox.Show("Invalid Score. Please try again.")
TextBox1.Focus()
TextBox1.SelectAll()
End If
End Sub
Sorry, but I forgot to mention in the original post that I am
restricted to using an InputBox (pop up dialog box) and cannot use a
textbox (embedded in the UI). The button must trigger an input box to
pop up. The score must be in a listbox. Anything else is allowed
Here's another version, then:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
Dim valid As Boolean
Dim intRunningTotal As Integer = 0
For inning As Integer = 1 To 7
Do
valid = False
Dim strResponse As String = InputBox("Enter the score of inning " + inning.ToString() & ": ", "Score")
Dim intScore As Integer
If Integer.TryParse(strResponse, intScore) Then
If intScore >= 0 Then
valid = True
intRunningTotal = intRunningTotal + intScore
ListBox1.Items.Add(inning.ToString() + vbTab + intScore.ToString() + vbTab + intRunningTotal.ToString())
Else
MessageBox.Show("Score must be greater than or equal to zero.")
End If
Else
MessageBox.Show("Invalid Score. Please try again.")
End If
Loop While Not valid
Next
End Sub
The same issue is occurring from the other users code in the code
provided where you cannot break out of the input box on command if
cancel or the x is clicked, it will show up as invalid score instead
of breaking out.
You didn't list that as a requirement. There is no difference between an empty input and clicking "OK", versus when the "X" or Cancel has been clicked. You can check for a blank string being returned, and drop out like this:
Dim strResponse As String = InputBox("Enter the score of inning " + inning.ToString() & ": ", "Score")
If strResponse = "" Then
Exit For ' ...or Exit Sub
End If
This is a well known limitation of InputBox, and one the reasons it is rarely used...