My program asks the user to input a number from 1 - 10 in a text box in. When I the user inputs the number I have it converted into an int
, by using this:
if (!int.TryParse(inputBox.Text, out input))
I used the !
because if the number cannot be TryParse
'd into a int it throws an error to the user.
This works, until I enter a number that begins with a +
, for example +5
, or +1
. It isn't catching the fact that there is a +
in front of the int
. If I enter more than one +
it throws an error like it should.
How would someone make an error proofing line(s) of code that checks for this type of input?
I think you want to allow 1-10 without the positive sign (+).
int number;
var input = numberTextBox.Text;
if (!input.StartsWith("+") && int.TryParse(input, out number))
{
//valid input, check if it's between 1-10
}
But I think the requirement is really strange. "+10" is considered the same as "10", it is a valid input.