-2
 // if user input is negative
 if (h < 0)
 {
     // assign absolute version of user input
     number = Math.Abs(n);
     pictureBox14.Visible = true;
}
else
{
    // else assign user input
        number = n;
    number = 0; // if user input is not an int then set number to 0  
    pictureBox6.Visible = true;
}

What is the correct code for validating to int ONLY? That integer is the only one I want to input in the textbox then the picturebox will appear.

arserbin3
  • 6,010
  • 8
  • 36
  • 52
Dave
  • 9
  • 1
  • 6

4 Answers4

0

Use int.TryParse method

int value= 0;

        if (int.TryParse(n, out value))
        {
            if (value< 0)
                number = Math.Abs(value);
            else
                number = value;
        }
Balaji Marimuthu
  • 1,940
  • 13
  • 13
0

There is no need for a complicated if statement. You can do it like this.

int number = 0;
bool isValid = int.TryParse(userInputString, out number);
number = Math.Abs(number);

if (isValid)
{
    pictureBox14.Visible = true;
}
Ghasan غسان
  • 5,577
  • 4
  • 33
  • 44
0

You first want to parse user Input, then validate the range:

int ExampleFunc( string userInput )
{
    int nVal;
    if( int.TryParse( userInput, out nVal ) )
    {
        return Math.Abs( nVal );
    }
    else return 0;
}
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
Fildor
  • 14,510
  • 4
  • 35
  • 67
  • He uses already the numbers `h` and `n`, so i doubt that string conversion helps – Tim Schmelter Jan 31 '17 at 14:58
  • @TimSchmelter He talks about getting a value from a TextBox, though. – Fildor Jan 31 '17 at 14:59
  • @TimSchmelter See "number = 0; // if user input is not an int then set number to 0" how else would you deal with that comment? A variable that already is int cannot be "not int" ... right? – Fildor Jan 31 '17 at 15:02
0

There's no reason to check if the number is negative, just always use the absolute value. Convert will return a 0 value if the string passed to it from the text input cannot be converted properly, so this code handles your question in just one line. If you want the picture box to show based on the int value, test that after the conversion.

int number = Math.Abs(Convert.ToInt32(textInput));
Andrew
  • 1,544
  • 1
  • 18
  • 36