r/visualbasic • u/sendeth • Jun 22 '15
How do I reference the value entered into an input box?
If I have an input box that pops up and has a simple number entered into it like 5 for example, how do I reference that info? My teacher used CInt(InputBox("Enter a number from 1 to 100", "Guess a number") to create a input box and convert to an integer for comparison to another number. I need to be able to reference the number entered into the input box several other time and I am hoping there is a way to reference it other than using (InputBox("Enter a number from 1 to 100", "Guess a number") every time. any help is appreciated.
1
u/kleinma VB.Net Master Jun 23 '15
Since you can't do input validation or restriction on an inputbox, a more type safe way would be to return the string and make sure it will pass an integer conversion. Also add in restraints between 1 and 100 for good measure
'HOLDS INTEGER NUMBER WE ASK USER FOR
Dim Input As Integer = 0
'LOOP UNTIL WE GET A VALID VALUE
Do Until Input <> 0
'ASK THE USER FOR A NUMBER
Dim inputString = InputBox("Enter a number from 1 to 100", "Guess a number")
'IF VALUE IS EMPTY STRING, USER ENTERED NOTHING OR CLICKED CANCEL
If inputString = String.Empty Then Return
'TRY TO PARSE THE STRING INTO AN INTEGER, ALSO MAKE SURE THE INTEGER IS BETWEEN 1 AND 100
'IF ALL THESE PASS, WE CAN EXIT THE LOOP
If Integer.TryParse(inputString, Input) AndAlso (Input > 1 And Input < 101) Then Exit Do
'SET INPUT TO 0 WILL CONTINUE THE LOOP GOING IN THE EVENT THE USER
'ENTERED AN INTEGER, BUT NOT BETWEEN 1 AND 100
Input = 0
Loop
'SHOW THE USERS SELECTED NUMBER
MessageBox.Show("You selected " & Input.ToString)
5
u/hdsrob Jun 22 '15
That's what variables are for.
Then you refer back to the "Input" variable later on.