Captain Caboose Captain Caboose - 1 month ago 6
Vb.net Question

Input Box Value system

Private Sub btnConfirmInfantry_Click(sender As Object, e As EventArgs) Handles btnConfirmInfantry.Click
Dim input = InputBox("How many do you want to attack with?", "Choose how many Infantry:")
Dim infantry As Integer
If (input > frmMainGame.lblInfantryNumberPlayer.Text) Then
MessageBox.Show("Error: The inputted number has to be <= current number of infantry.")
Else

If Integer.TryParse(input, infantry) Then
Dim hpai = Integer.Parse(frmMainGame.lblHPAI.Text, Globalization.NumberStyles.AllowThousands, Globalization.CultureInfo.InvariantCulture)
frmMainGame.lblHPAI.Text = String.Format("{0:n0}", hpai - infantry * 2)

Dim numPlayer = frmMainGame.lblInfantryNumberPlayer.Text 'Integer.Parse(frmMainGame.lblInfantryNumberPlayer.Text)
frmMainGame.lblInfantryNumberPlayer.Text = (numPlayer - input).ToString("N0")

End If
End If
End Sub


I am attempting to get the If (input > frmMainGame.lblInfantryNumberPlayer.Text) Then Skip the rest of the line of code.
But, the issue is that the lblInfantry numbers are in the millions and it is only reading the first number which is 2. So if I input 3, the error msgbox will occur. I have tried the Globilization.NumberStyles.AllowThousands by putting it after the frm.... but that did not work. Any suggestions? Thanks!

Note: I want to put a input value of like 30 in and if the lblInfantry is like 100,000 then the msgbox will NOT occur and the code will read after the Else.

Answer

You need to convert your input values to integers. Using a comparative operator like > on strings will do the comparison alphabetically, so for example, "20000" < "3" returns true - alphabetically, 20000 comes first.

Dim intInfanty as int = 0;
Dim intInput as int = 0;
Dim txt as String = frmMainGame.lblInfantryNumberPlayer.Text, intInfantry;

If Int.TryParse(input, intInput) AndAlso Int.TryParse(txt, intInfantry) Then
    If (intInput > intInfantry)  Then
        'Input > InfantryNumberPlayer
    Else
        'Input <= InfantryNumberPlayer
    End If
Else
    'One of the values isn't an integer
End If

If you want to combine the If statements so that non-numeric values fall into the same else as the > comparison, you can do this:

Dim intInfanty as int = 0;
Dim intInput as int = 0;
Dim txt as String = frmMainGame.lblInfantryNumberPlayer.Text, intInfantry;

If Int.TryParse(input, intInput) AndAlso Int.TryParse(txt, intInfantry) AndAlso (intInput > intInfantry) Then
    'Input > InfantryNumberPlayer
Else
    'Input <= InfantryNumberPlayer
    'OR one of the values is not a valid number
End If
Comments