Search code examples
c#if-statementtextbox

C# IF that checks wether a textbox input is greater than 0 and also checks if it's an integer(Numeric)


I made a scoreboard where the user inputs the max number of points allowed in a textBox1. I have two buttons. The left one increases the value on the left side of a label and the right one increases the value on the right side of the label. Once one side reaches the maximum number of points I declare the winner using a MessageBox.

I want to know how to check if the user didn't input an integer in the textbox. I already made te condition for it to be greater than 0.

This is what I have: SCOREBOARD IMAGE

public void winner()
{
    int max = Convert.ToInt32(textBox1.Text);

    if (max <= 0 || //this is where i want to check if its an integer)
    {
        MessageBox.Show("Press RESET and use a value greater than 0");
        btn_left.Enabled = false;
        btn_right.Enabled = false;
        textBox1.ResetText();
    }
    else if (left == max)
    {
        MessageBox.Show("Winner: Left Player");
        textBox1.Enabled = false;
        btn_left.Enabled = false;
        btn_right.Enabled = false;
    }
    else if (right == max)
    {
        MessageBox.Show("Winner: Right Player");
        textBox1.Enabled = false;
        btn_left.Enabled = false;
        btn_right.Enabled = false;
    }
}

private void btn_left_Click(object sender, EventArgs e)
{
    left = left + 1;
    lbl_score.Text = left.ToString() + " - " + right.ToString();
    winner();
}

private void btn_right_Click(object sender, EventArgs e)
{
    right = right + 1;
    lbl_score.Text = left.ToString() + " - " + right.ToString();
    winner();
}

private void btn_reset_Click(object sender, EventArgs e)
{
    textBox1.Enabled = true;
    textBox1.Text = "0";
    btn_left.Enabled = true;
    btn_left.Enabled = true;
    left = 0;
    right = 0;
    lbl_score.Text = left.ToString() + " - " + right.ToString();
}

Edit: I checked the other solution suggested in the comments but none of the answers there seem to work for me except the one I selected in this thread


Solution

  • You need to parse the text to make sure its a number

     public void winner()
     {
    
          if (!int.TryParse(textBox1.Text, out int max))
          {
             MessageBox.Show("Dem numbers aren't numbers");
             return;
          }
    
          ...
    

    Int32.TryParse Method (String, Int32)

    Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.