14 Replies - 9757 Views - Last Post: 16 December 2008 - 04:20 PM Rate Topic: -----

#1 learningc#  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 07-December 08

how can i restrict the text box to only allow integers.

Posted 14 December 2008 - 04:14 PM

hii! im new to c# programming and im trying to create a maths Game. i have been trying to restrict the input of the answer into my text box as only integers..i will copy+paste my code below..but its not working! will anyone please be able to suggest any improvements and or new suggestions to make this work! Thanks in advance! :-)

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 MathGameCwk1
{
	public partial class MathGame : Form
	{
		RandomGenerator random = new RandomGenerator(); // random generate
		Boolean correctAnswer; //  used to calculate correct answer
		int limit;
		int pointsachieved;
		int limitquestion; // used to limit number of questions displayed
		int currentScore = 0; // score initalised to 0
		int Bnus;
		int totalscore;
		public Boolean CorrectAnswer
		{
			get { return correctAnswer; }
			set { correctAnswer = value; }
		}

		public MathGame()
		{
			InitializeComponent();
		}

		


		private void startbutton_Click(object sender, EventArgs e)
		{
			QuestionTimer.Start();

			GameTimer.Start();

			int value;  //


			for (value = 0; value != limit; value++)  //Until the "value" reaches 150 it will keep adding 1
			{
				QuestionTimer.Enabled = true;   //timer "wholeGame" is enabled 
				pgbar.Maximum = limit;
				pgbar2.Maximum = limit;
				QuestionTimer.Enabled = true;
				GameTimer.Enabled = true;

			}

			pgbar.Value = 0;
			pgbar2.Value = 0;
			redoRandom();   //calls the "redoRandom" method



			lbl1.Visible = true;	// Makes all these visable once "Start Game" is selected
			lbl2.Visible = true;
			lbl3.Visible = true;
			lblsymbol1.Visible = true;
			lblsymbol2.Visible = true;
			lblsymbol3.Visible = true;
			QuestionTimer.Enabled = true;
			pgbar.Value = 0;
			pgbar2.Value = 0;
			lblreportans.Visible = true;
			RefreshButton.Visible = true;
			QuitGame.Visible = true;
			anstxtbox.Visible = true;
			anstxtbox.Enabled = true;
			startbutton.Visible = false;
			lbllevelpanel.Visible = true;
			lblscorepanel.Visible = true;
			lblbonuspanel.Visible = true;
			lblnamepanel.Visible = true;
			crosspicbox.Visible = false;
			tickpicbox.Visible = false;
			lblreportans.Visible = true;
			lbla.Visible = false;
			lblb.Visible = false;
			lblc.Visible = false;
			pgbar.Visible = true;
			pgbar2.Visible = true;
			panel2.Visible = true;
			lblentername.Enabled = false;
			txb_nametbox.Enabled = false;
			lbllevel.Enabled = false;
			levelcombo.Enabled = false;
			lblgameover.Visible = true;
			lblreportime.Visible = true;

			lblnamepanel.Text = "NAME:" + txb_nametbox.Text; // displays name enterd
			lbllevelpanel.Text = "LEVEL:" + levelcombo.Text; // displays level selected


		}


		public void redoRandom() // restarts random generator
		{
			if (levelcombo.SelectedIndex == 0)
			{
				Easy();

			}

			else if (levelcombo.SelectedIndex == 1)
			{
				Medium();
			}

			else if (levelcombo.SelectedIndex == 2)
			{
				Hard();
			}
			pgbar.Value = 0;

			lblsymbol1.Text = random.generateRandomSymbol();
			lblsymbol2.Text = random.generateRandomSymbol();
			lblsymbol3.Text = random.generateRandomSymbol();
		}


		private void anstxtbox_TextChanged(object sender, EventArgs e) //reports answer
		{
			int a = Result();

			if (correctAnswer)
			{
				lblreportans.ForeColor = Color.Black;
				lblreportans.BackColor = Color.Green;
				crosspicbox.Visible = false;
				tickpicbox.Visible = true;
				lblreportans.Text = "Well Done!Next question!";
				anstxtbox.Clear();


				redoRandom();


				currentScore = currentScore + pointsachieved;

				totalscore = currentScore + Bnus;
				lbltotalscorepanel.Text = "TOTAL SCORE: " + totalscore.ToString();
				lblscorepanel.Text = "SCORE: " + currentScore.ToString();
				lblbonuspanel.Text = "BONUS: " + Bnus.ToString(); // displays bonus


			}




			else
			{
				lblreportans.ForeColor = Color.Black;
				lblreportans.BackColor = Color.HotPink;
				lblreportans.Text = "Try Again..Time's Ticking!";
				crosspicbox.Visible = true;
				tickpicbox.Visible = false;
			}

			correctAnswer = false;


		}

		private void anstxtbox_KeyPress(object sender, KeyPressEventArgs e)
		{

			string[] nums = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };

			if (!nums.Contains(e.KeyChar.ToString()))

				e.Handled = true;

			else
			{
			}
		}




Is This A Good Question/Topic? 0
  • +

Replies To: how can i restrict the text box to only allow integers.

#2 s3thst4  Icon User is offline

  • a * a = (b * b) + (c * c) - 2(b)(c)cos(A)
  • member icon

Reputation: 10
  • View blog
  • Posts: 587
  • Joined: 20-November 08

Re: how can i restrict the text box to only allow integers.

Posted 14 December 2008 - 04:26 PM

View Postlearningc#, on 14 Dec, 2008 - 03:14 PM, said:

hii! im new to c# programming and im trying to create a maths Game. i have been trying to restrict the input of the answer into my text box as only integers..i will copy+paste my code below..but its not working! will anyone please be able to suggest any improvements and or new suggestions to make this work! Thanks in advance! :-)

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 MathGameCwk1
{
	public partial class MathGame : Form
	{
		RandomGenerator random = new RandomGenerator(); // random generate
		Boolean correctAnswer; //  used to calculate correct answer
		int limit;
		int pointsachieved;
		int limitquestion; // used to limit number of questions displayed
		int currentScore = 0; // score initalised to 0
		int Bnus;
		int totalscore;
		public Boolean CorrectAnswer
		{
			get { return correctAnswer; }
			set { correctAnswer = value; }
		}

		public MathGame()
		{
			InitializeComponent();
		}

		


		private void startbutton_Click(object sender, EventArgs e)
		{
			QuestionTimer.Start();

			GameTimer.Start();

			int value;  //


			for (value = 0; value != limit; value++)  //Until the "value" reaches 150 it will keep adding 1
			{
				QuestionTimer.Enabled = true;   //timer "wholeGame" is enabled 
				pgbar.Maximum = limit;
				pgbar2.Maximum = limit;
				QuestionTimer.Enabled = true;
				GameTimer.Enabled = true;

			}

			pgbar.Value = 0;
			pgbar2.Value = 0;
			redoRandom();   //calls the "redoRandom" method



			lbl1.Visible = true;	// Makes all these visable once "Start Game" is selected
			lbl2.Visible = true;
			lbl3.Visible = true;
			lblsymbol1.Visible = true;
			lblsymbol2.Visible = true;
			lblsymbol3.Visible = true;
			QuestionTimer.Enabled = true;
			pgbar.Value = 0;
			pgbar2.Value = 0;
			lblreportans.Visible = true;
			RefreshButton.Visible = true;
			QuitGame.Visible = true;
			anstxtbox.Visible = true;
			anstxtbox.Enabled = true;
			startbutton.Visible = false;
			lbllevelpanel.Visible = true;
			lblscorepanel.Visible = true;
			lblbonuspanel.Visible = true;
			lblnamepanel.Visible = true;
			crosspicbox.Visible = false;
			tickpicbox.Visible = false;
			lblreportans.Visible = true;
			lbla.Visible = false;
			lblb.Visible = false;
			lblc.Visible = false;
			pgbar.Visible = true;
			pgbar2.Visible = true;
			panel2.Visible = true;
			lblentername.Enabled = false;
			txb_nametbox.Enabled = false;
			lbllevel.Enabled = false;
			levelcombo.Enabled = false;
			lblgameover.Visible = true;
			lblreportime.Visible = true;

			lblnamepanel.Text = "NAME:" + txb_nametbox.Text; // displays name enterd
			lbllevelpanel.Text = "LEVEL:" + levelcombo.Text; // displays level selected


		}


		public void redoRandom() // restarts random generator
		{
			if (levelcombo.SelectedIndex == 0)
			{
				Easy();

			}

			else if (levelcombo.SelectedIndex == 1)
			{
				Medium();
			}

			else if (levelcombo.SelectedIndex == 2)
			{
				Hard();
			}
			pgbar.Value = 0;

			lblsymbol1.Text = random.generateRandomSymbol();
			lblsymbol2.Text = random.generateRandomSymbol();
			lblsymbol3.Text = random.generateRandomSymbol();
		}


		private void anstxtbox_TextChanged(object sender, EventArgs e) //reports answer
		{
			int a = Result();

			if (correctAnswer)
			{
				lblreportans.ForeColor = Color.Black;
				lblreportans.BackColor = Color.Green;
				crosspicbox.Visible = false;
				tickpicbox.Visible = true;
				lblreportans.Text = "Well Done!Next question!";
				anstxtbox.Clear();


				redoRandom();


				currentScore = currentScore + pointsachieved;

				totalscore = currentScore + Bnus;
				lbltotalscorepanel.Text = "TOTAL SCORE: " + totalscore.ToString();
				lblscorepanel.Text = "SCORE: " + currentScore.ToString();
				lblbonuspanel.Text = "BONUS: " + Bnus.ToString(); // displays bonus


			}




			else
			{
				lblreportans.ForeColor = Color.Black;
				lblreportans.BackColor = Color.HotPink;
				lblreportans.Text = "Try Again..Time's Ticking!";
				crosspicbox.Visible = true;
				tickpicbox.Visible = false;
			}

			correctAnswer = false;


		}

		private void anstxtbox_KeyPress(object sender, KeyPressEventArgs e)
		{

			string[] nums = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };

			if (!nums.Contains(e.KeyChar.ToString()))

				e.Handled = true;

			else
			{
			}
		}




Try this, learningc# :

Make the variable to get what's in the textbox a global variable. Put it before the first event.
Then, go to the textbox where they type and double click it.
It gets to the TextChanged event.
Then, type this in.

try
{
  what your variable does // for example, 'userinput = int.Parse(textBox1.Text);'
} 
catch
{
  MessageBox.Show("Error!");
}


This tries the variable for any possible error, which one of the errors is entering a string.
Tell me if I helped :)

Also, the catch is what is displayed when they enter something that is not supposed to be entered. You can make whatever you want.

~ Seth

This post has been edited by s3thst4: 14 December 2008 - 04:28 PM

Was This Post Helpful? 0
  • +
  • -

#3 Core  Icon User is offline

  • using System.Linq;
  • member icon

Reputation: 764
  • View blog
  • Posts: 5,095
  • Joined: 08-December 08

Re: how can i restrict the text box to only allow integers.

Posted 14 December 2008 - 04:33 PM

Just use the MaskedTextBox control instead of the standard TextBox and set it's mask to integer numbers.
Was This Post Helpful? 0
  • +
  • -

#4 learningc#  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 07-December 08

Re: how can i restrict the text box to only allow integers.

Posted 14 December 2008 - 05:17 PM

hi there! thanks for your reply! i tried doing wot u suggested but i end up getting and error saying cannot convert int to bool.





Try this, learningc# :

Make the variable to get what's in the textbox a global variable. Put it before the first event.
Then, go to the textbox where they type and double click it.
It gets to the TextChanged event.
Then, type this in.

try
{
  what your variable does // for example, 'userinput = int.Parse(textBox1.Text);'
} 
catch
{
  MessageBox.Show("Error!");
}


This tries the variable for any possible error, which one of the errors is entering a string.
Tell me if I helped :)

Also, the catch is what is displayed when they enter something that is not supposed to be entered. You can make whatever you want.

~ Seth
[/quote]


heyy there! thanks for your reply!! i did change try to change it to a masked text box, but when you mentioned about setting its mask to integer numbers, how would i go about doing that..?

Thanks again!


View PostCore, on 14 Dec, 2008 - 03:33 PM, said:

Just use the MaskedTextBox control instead of the standard TextBox and set it's mask to integer numbers.

Was This Post Helpful? 0
  • +
  • -

#5 Core  Icon User is offline

  • using System.Linq;
  • member icon

Reputation: 764
  • View blog
  • Posts: 5,095
  • Joined: 08-December 08

Re: how can i restrict the text box to only allow integers.

Posted 14 December 2008 - 09:35 PM

Find the Mask property of the MaskedTextBox and set its mask using zeroes, where a 0 stands for a digit. For example, if you set the mask to 00000, it would stand for a 5-digit integer.
Was This Post Helpful? 0
  • +
  • -

#6 learningc#  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 07-December 08

Re: how can i restrict the text box to only allow integers.

Posted 15 December 2008 - 06:14 AM

o ye i did do that, but is there any way of allowing negative numbers too?



View PostCore, on 14 Dec, 2008 - 08:35 PM, said:

Find the Mask property of the MaskedTextBox and set its mask using zeroes, where a 0 stands for a digit. For example, if you set the mask to 00000, it would stand for a 5-digit integer.

Was This Post Helpful? 0
  • +
  • -

#7 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1511
  • View blog
  • Posts: 5,916
  • Joined: 21-March 08

Re: how can i restrict the text box to only allow integers.

Posted 15 December 2008 - 07:05 AM

or you can use this...

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar >= 48 && e.KeyChar <= 57)
    {
        e.Handled = false;
    }
    else
    {
        e.Handled = true;
    }
}


Was This Post Helpful? 0
  • +
  • -

#8 Core  Icon User is offline

  • using System.Linq;
  • member icon

Reputation: 764
  • View blog
  • Posts: 5,095
  • Joined: 08-December 08

Re: how can i restrict the text box to only allow integers.

Posted 15 December 2008 - 03:38 PM

View Postlearningc#, on 15 Dec, 2008 - 05:14 AM, said:

o ye i did do that, but is there any way of allowing negative numbers too?


Set the mask property to #000000 (where the number of zeroes will represent the maximum length of the integer and the # symbol will be for a + or - sign).
Was This Post Helpful? 0
  • +
  • -

#9 learningc#  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 07-December 08

Re: how can i restrict the text box to only allow integers.

Posted 15 December 2008 - 03:59 PM

hi there! thanks sooo much!!!!!!!! it worked! :D :^:

Thanks again!!




View PostCore, on 15 Dec, 2008 - 02:38 PM, said:

View Postlearningc#, on 15 Dec, 2008 - 05:14 AM, said:

o ye i did do that, but is there any way of allowing negative numbers too?


Set the mask property to #000000 (where the number of zeroes will represent the maximum length of the integer and the # symbol will be for a + or - sign).

Was This Post Helpful? 0
  • +
  • -

#10 learningc#  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 07-December 08

Re: how can i restrict the text box to only allow integers.

Posted 15 December 2008 - 04:39 PM

hi there! im trying to restrict my text box to allow + and - integers. the following code only allows positive. how can i amend it to allow negative integers too?
private void anstxtbox_KeyPress(object sender, KeyPressEventArgs e)
		{
			const char Delete = (char)8;
			e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
		}


Was This Post Helpful? 0
  • +
  • -

#11 fremgenc  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 119
  • Joined: 15-November 07

Re: how can i restrict the text box to only allow integers.

Posted 15 December 2008 - 05:08 PM

private void anstxtbox_KeyPress(object sender, KeyPressEventArgs e)
		{
			const char Delete = (char)8;
			if(!Char.IsDigit(e.KeyChar) && e.KeyChar != Delete)
			{//same as your code so far
				   e.Handled = true;
			 }
			 else if (e.KeyChar == '-' && anstxtbox.Text.Length == 0)
							  //1*								2*
					e.Handled =  true;

  //1 -  is the entered character a negative sign? '-'
  //2 -  is the character the first to be entered in the text box?
		}



hope this helps!
Was This Post Helpful? 0
  • +
  • -

#12 Jayman  Icon User is offline

  • Student of Life
  • member icon

Reputation: 415
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: how can i restrict the text box to only allow integers.

Posted 15 December 2008 - 06:30 PM

Topics merged. Please do not create duplicate topics.
Was This Post Helpful? 0
  • +
  • -

#13 learningc#  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 07-December 08

Re: how can i restrict the text box to only allow integers.

Posted 16 December 2008 - 04:45 AM

hey! that didnt work :(...thanks for the reply anyway!!!





View Postfremgenc, on 15 Dec, 2008 - 04:08 PM, said:

private void anstxtbox_KeyPress(object sender, KeyPressEventArgs e)
		{
			const char Delete = (char)8;
			if(!Char.IsDigit(e.KeyChar) && e.KeyChar != Delete)
			{//same as your code so far
				   e.Handled = true;
			 }
			 else if (e.KeyChar == '-' && anstxtbox.Text.Length == 0)
							  //1*								2*
					e.Handled =  true;

  //1 -  is the entered character a negative sign? '-'
  //2 -  is the character the first to be entered in the text box?
		}



hope this helps!

Was This Post Helpful? 0
  • +
  • -

#14 fremgenc  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 119
  • Joined: 15-November 07

Re: how can i restrict the text box to only allow integers.

Posted 16 December 2008 - 09:00 AM

Why? what is error? or no error?

you are very specific! [/sarcasm]
Was This Post Helpful? 0
  • +
  • -

#15 learningc#  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 07-December 08

Re: how can i restrict the text box to only allow integers.

Posted 16 December 2008 - 04:20 PM

hi there! im sorry!!..should'v mentioned that there is no error...but im still not able to type in the "-" sign into the text box.

View Postfremgenc, on 16 Dec, 2008 - 08:00 AM, said:

Why? what is error? or no error?

you are very specific! [/sarcasm]

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1