-3

I've just started out with coding and I'm looking at making a simple Higher/Lower game. I have a random start number, and a new number set up when the 'higher' or 'lower' buttons are clicked. What I want to say though is....

If the person clicks the higher button: If NewNumberLbl is greater than round1numberlbl. then do something. Thing is im getting the issue of not being able to say

If {NewNumberLbl.Text > Round1NumberLbl.Text}
{}

because I'm getting the error:

Error 1 Operator '>' cannot be applied to operands of type 'string' and 'string'

so how do I go about fixing this and making it into a type int?

Ps I was trying to create new int's , associate them with the ints within the random number methods and then call them instead?

HELP!

public Round1()
{
    InitializeComponent();
    RandomNumber(0, 12);
    NewNumberLbl.Visible = true;
}

public void RandomNumber(int min, int max)
{
    int num = new Random().Next(min, max);
    Round1NumberLbl.Text = num.ToString();
}

public void RandomNumber2(int min, int max)
{
    int num2 = new Random().Next(min, max);
    NewNumberLbl.Text = num2.ToString();
}

private void Round1HBtn_Click(object sender, EventArgs e)
{
    //RandomNumber2(0, 12);
    //if (newNumber >= originalNumber) 
    //{

    //}
}
MPelletier
  • 16,256
  • 15
  • 86
  • 137
  • 8
    Are you seriously telling me you couldn't look this up on Google (or on StackOverflow)? – Ant P Jan 23 '14 at 12:35
  • 1
    Few hints: use numeric data type such as int to compare the values using operators such as < and >. Also, let your methods return an int instead of void and use that result. Also, your 2 methods are almost identical. Try to use only one. – NoChance Jan 23 '14 at 12:41

5 Answers5

3

Converting a string to a int:

int i;
if (int.TryParse("1234", out i){
    //ok
}
Peter
  • 27,590
  • 8
  • 64
  • 84
  • 1
    I like using the TryParse as it adds some defense in case the string is contains characters other than a number. I posted a good MSDN reference in my answer the OP should read and digest. +1 for first answer peer. – websch01ar Jan 23 '14 at 12:40
2

You can use:

Convert.ToInt32(myString);

or:

int myOut;
int.TryParse(myString, out myOut);

The first one will throw an exception if you try to convert something thats not parseable in an int.

The second one will result in 0 if the conversion is not successful

1

http://msdn.microsoft.com/en-us/library/bb397679.aspx Try this:- Convert.ToInt32(input);

Example:

if (Convert.ToInt32(LblnewNumber.Text) >= Convert.ToInt32(LbloriginalNumber.Text)) 
        {

        }
wruckie
  • 1,717
  • 1
  • 23
  • 34
variable
  • 8,262
  • 9
  • 95
  • 215
0

int.Parse(NewNumberLbl.Text);

You should however make sure the label has a number and not some other character.

Ricardo Appleton
  • 679
  • 10
  • 22
0
string text = "500";
int num = int.Parse(text);

This should work. And you can use TryParse to check "text" is valid

Erkan Akın
  • 106
  • 5