Hi, I'm new to C# and trying to program myself a number guessing game. I've got a troubling problem with data type formats..

Here is my code

 private void btnOk_Click(object sender, EventArgs e)
    {

        String invalue;   
         int guessedNumber;
         int secretNumber = RandomNumber(1, 100);

         do
         {
             invalue = textBox1.Text;
             guessedNumber = int.Parse(invalue);   --- I got an error here

             if (guessedNumber == secretNumber)
             {

                 MessageBox.Show("Correct guess!");

             }
             else if (guessedNumber < secretNumber)
             {
                 MessageBox.Show("Higher than that!");
                 textBox1.Clear();
             }
             else if (guessedNumber > secretNumber)
             {
                 MessageBox.Show("Lower than that!");
                 textBox1.Clear();
             }

         } while (guessedNumber != secretNumber);
     }

Any help would be appreciated much.. thank you

Edited 4 Years Ago by Ezzaral: Code formatting

Instead of using:

invalue = textBox1.Text;

guessedNumber = int.Parse(invalue);

use:

guessedNumber = Convert.ToInt32(textBox1.text);

Hope this helps

edit: if you enter any charactors into the textbox you will get an error because charactors cannot be converted into a numerice value the way you wish, you may have to do a check when anything is entered into the textbox to check it is only numeric.

Edited 4 Years Ago by ChrisHunter

Are you sure you're not adding any non-numeric values to that box?
Can you .Trim() it first and/or use ChrisHunter's suggestion?

Try using TryParse method:

invalue = textBox1.Text;
if(int.TryParse(invalue, out guessedNumber))
{
    //contine here
}
else
    MessageBox("Input value is not a number.");

Edited 4 Years Ago by Mitja Bonca: added code

Edit: Mitja Bonca beat me to it!

An alternate way to carry out ChrisHunter's suggestion, including handling for non-numeric input would be a TryParse.

    int guessedNumber;
    bool parseSucceeded = Int32.TryParse(textBox1.Text, guessedNumber);

This will set the bool parseSucceeded to true if the text in textBox1.Text was numeric and could be converted, else the result will be false and you can take action on this value with a loop or something similar.

See here for the MSDN Article on this method.

Edited 4 Years Ago by Mike Askew: Edit

bettyburns said:
a number ^^, i typed 56 and then it threw an error message.

If you would insert56 - numbers only, there will be surely no Error warning. You must insert some other character then numeric, so you are throuwn this kind of error. And character that is not numeric, cannot be parsed or converted ito integer.
Try using my method (int.TryParse()), you will see what it happens.
But I repeat - if you insert numeric characters only, and parsing to integer, there will surely be no error. Else, it will be.
You can even try with:

Int32.Parse();

Hey thanks for helping me guys, I'm bothered when I typed an integer(34) the messagebox didn't disappear when I clicked the ok button. What's the problem with that?

There is really a problem in your do-while loop. You can NOT have it in windows forms.
Why?
Simply, when you clicked the button, you cannot edit your variable any longer, so the while loop will be infinitive.
While loop can be in console, but now here, in this kind of form like you have it.

This is how you should do in win form:

        Random RandomNumber = new Random();
        bool bGuessed;
        int guessedNumber;
        int secretNumber;
        int counter;
        private void button2_Click(object sender, EventArgs e)
        {
            //1st click the button to set new number, then start guessing!
            if (!bGuessed)
            {
                //set to new number (but only after pevious one was guessed!
                secretNumber = RandomNumber.Next(1, 11);
                MessageBox.Show("New round is starting. Guess new number from 1 to 10.");
                bGuessed = true;                
            }
            else
            {
                if (int.TryParse(textBox1.Text.Trim(), out guessedNumber))
                {
                    if (guessedNumber == secretNumber)
                    {
                        MessageBox.Show("Correct guess!\r\nYou needed " + counter + " clicks.");
                        counter = 0;
                        bGuessed = false;                        
                    }
                    else if (guessedNumber < secretNumber)
                    {
                        MessageBox.Show("Higher than that!");
                        counter++;
                    }
                    else if (guessedNumber > secretNumber)
                    {
                        MessageBox.Show("Lower than that!");                        
                        counter++;
                    }
                }
                else
                    MessageBox.Show("This is not a number.");
            }
            Clering_Focusing();
        }

        private void Clering_Focusing()
        {
            textBox1.Clear();
            textBox1.Focus();
        }

Hope it helps,
bye

Random RandomNumber = new Random();
bool bGuessed;
int guessedNumber;
int secretNumber;
int counter;
private void button2_Click(object sender, EventArgs e)
{
//1st click the button to set new number, then start guessing!
if (!bGuessed)
{
//set to new number (but only after pevious one was guessed!
secretNumber = RandomNumber.Next(1, 11);
MessageBox.Show("New round is starting. Guess new number from 1 to 10.");
bGuessed = true;
}
else
{
if (int.TryParse(textBox1.Text.Trim(), out guessedNumber))
{
if (guessedNumber == secretNumber)
{
MessageBox.Show("Correct guess!\r\nYou needed " + counter + " clicks.");
counter = 0;
bGuessed = false;
}
else if (guessedNumber < secretNumber)
{
MessageBox.Show("Higher than that!");
counter++;
}
else if (guessedNumber > secretNumber)
{
MessageBox.Show("Lower than that!");
counter++;
}
}
else
MessageBox.Show("This is not a number.");
}
Clering_Focusing();
}
private void Clering_Focusing()
{
textBox1.Clear();
textBox1.Focus();
}

hi Mitja..thanks for your help, by the way, there are few errors on your code, I changed it into like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NumberGame
{

    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            randomNumber = number.Next(1, 101);
        }
        Random number = new Random(); // This is declaring number; our randomizer
        int randomNumber; // Our randomized number
        int guessedNumber; // Our guessed number
        int tries = 0;
        bool bGuessed;

        private void btnOk_Click(object sender, EventArgs e)
        {


            guessedNumber = int.Parse(textBox1.Text);

            if (!bGuessed)
            {
                bGuessed = true;
            }
            else
                if (int.TryParse(textBox1.Text.Trim(), out guessedNumber))
                {
                    tries++;
                    if (guessedNumber < randomNumber)
                    {
                        MessageBox.Show("higher than " + guessedNumber);
                        textBox1.Clear();
                        textBox1.Focus();

                    }
                    else if (guessedNumber > randomNumber)
                    {
                        MessageBox.Show("lower than " + guessedNumber);
                        textBox1.Clear();
                        textBox1.Focus();
                    }

                    else

                        MessageBox.Show("You guessed correctly! You have guessed " + tries + " times to find the magic number.", "You win!", MessageBoxButtons.OK);
                    bGuessed = false;
                    textBox1.Clear();
                    textBox1.Focus();
                }
                else
                    MessageBox.Show("Not an integer!");

            }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
         //   if (textBox1.Text != "")
        //    {
         //      try
           //     {
           //         guessedNumber = int.Parse(textBox1.Text);
           //     }
           //     catch
           //     {
           //         MessageBox.Show("Please enter an integer from 1-100", "Error!");
            //        textBox1.Clear();
            //    }
            //}


        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            textBox1.Focus();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            return;
        }




        } // end main

    }

and it works! thanks

Edited 3 Years Ago by mike_2000_17: Fixed formatting

This article has been dead for over six months. Start a new discussion instead.