0

I can't get the string of text_box.text to convert to an int then compare to another int.

I also need to check to see if the string of text_box.text can be turned into an int.

I've tried .ToInt32, which I have always used and it has been fine. I have no idea how to test if the string of text_box can be turned into an int.

public static void before (int bS)
{
    beforeScore = bS;
}

//some space later

if (score_bet_text_box.Text.ToInt32() > beforeScore)
{
    MessageBox.Show("You can't bet more than you have", "game");
}

I expect it to convert the string of text_box into an int, then compare it to the other int.

I also hope to test if it can be converted into an int, but have no clue how so it is not shown in the code above.

Aref
  • 746
  • 10
  • 27
JD M
  • 65
  • 1
  • 1
  • 8
  • TextBox.Text is just a string. It does _not_ have a `ToInt32()` method. Look into the [`Int32.Parse()`](https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse) and [`Int32.TryParse()`](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse) methods. You use the former one when you're certain the string is, in fact, convertible to `Int32` and you use the latter when you're not certain which seems to be the case. – 41686d6564 stands w. Palestine Apr 29 '19 at 22:58
  • 1
    Use Int32.TryParse(). You can find a lot of examples here on StackOverflow – 15ee8f99-57ff-4f92-890c-b56153 Apr 29 '19 at 23:09
  • @AhmedAbdelhameed: it would be a nice extension method though ;-) – Stefan Apr 29 '19 at 23:16

1 Answers1

2

ToInt32 isn't a method on a string unless you have an extension method somewhere. You want to use the TryParse method as follows...

if(int.TryParse(score_bet_text_box.Text, out int result))
{
    if(result > beforeScore)
    {
        MessageBox.Show("You can't bet more than you have", "game");
    }
}

If you are using an older version of C# you'll have to define result outside the if as follows:

int result;
if(int.TryParse(score_bet_text_box.Text, out result))
Fabulous
  • 2,393
  • 2
  • 20
  • 27