-1

I'm receiving some user input through a TextBox which is then being converted to an int so it can be used in further calculations when I click the Calculate button.

I have checked to see if the TextBox is empty when the Calculate button is clicked, if it is, then a message box appears. Now I realised I need to check to make sure it is a number being input, not a letter. I'm looking for something similar to this

if(hoursInput.Text == "" || hoursInput.Text contains "a-z")
{
    \\ handle error
}
else
{
    \\ continue with code
}

EDIT:

The user input is converted to an int in the else block, but I do not want the function to reach this stage of converting from string to int if the user input contains letters, which is why I want to check to see if the user input contains any letters in the if block

Donald
  • 117
  • 6

2 Answers2

0

As mentioned, use Int32.TryParse which will return a bool of whether or not the input could be parsed to an Int32. One of the parameters is an out and will become the Int32 if the input could be parsed.

See: https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx

if(hoursInput.Text == "" || !Int32.TryParse(hoursInput.Text, out number))
{
\\ handle error
}
else
{
\\ continue with code
}
0

You really don't need to check anything explicitly:

int aNumber;
if (!Int32.TryParse(hoursInput.Text, out aNumber)) {
    // handle error
} else {
    // handle `aNumber`
}
zerkms
  • 249,484
  • 69
  • 436
  • 539