|
-
July 9th, 2009, 02:27 PM
#1
Input Type Check
I'm creating a simple application just for the benefit on learning and I need a way to bring up and error message if the user enters in a string instead of an integer on this variable:
Code:
int guess = Convert.ToInt32(txtGuess.Text);
I have a try statement just after this but the problem is of course and error occurs before that. However if i put this variable inside the try statement nothing else can access it.
Code:
try
{
if (guess > 1000 || guess < 0)
{
throw new ArgumentException();
}
else if (guess.GetType().Name != "Int32")
{
throw new FormatException();
}
}
How can i prevent the user from entering in anything other than an integer? Thanks for any help
-
July 9th, 2009, 02:43 PM
#2
Re: Input Type Check
The parsing is throwing the exception, so that obviously needs to be inside of the try block. Catch the FormatException and show a message. Also, there is no need to throw an exception to catch it in the "catch" block, just handle the error there.
However, it is better to simply not allow the use to enter the invalid data in the first place. You can do this by handling the KeyPress event and setting the KeyPressEventArgs' Handled property accordingly, or you can use a masked textbox.
-
July 9th, 2009, 08:28 PM
#3
Re: Input Type Check
You can do a regex check first to avoid some errors, and it's regex, so it matches or it doesn't, no error unless text field is blank or expression is bad.
Of course, my code might not be the solution you are looking for, but it's a step. You can change the event to whatever you like.
Code:
namespace CodeGuru
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonCheck_Click(object sender, EventArgs e)
{
Regex check = new Regex("[0-9]+");
String text = textBox1.Text;
if (text.Length > 0)
{
Match match = check.Match(text);
Int32 guess = Int32.Parse(match.Value);
MessageBox.Show(guess.ToString());
}
}
}
}
Last edited by code?; July 9th, 2009 at 08:39 PM.
-
July 9th, 2009, 10:12 PM
#4
Re: Input Type Check
 Originally Posted by code?
You can do a regex check first to avoid some errors, and it's regex, so it matches or it doesn't, no error unless text field is blank or expression is bad.
Of course, my code might not be the solution you are looking for, but it's a step. You can change the event to whatever you like.
Code:
namespace CodeGuru
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonCheck_Click(object sender, EventArgs e)
{
Regex check = new Regex("[0-9]+");
String text = textBox1.Text;
if (text.Length > 0)
{
Match match = check.Match(text);
Int32 guess = Int32.Parse(match.Value);
MessageBox.Show(guess.ToString());
}
}
}
}

that code throws an error for me. The problem is that if the guess is not an integer, the "match.Value" is blank. The parsing of a blank string will fail.
-
July 9th, 2009, 10:25 PM
#5
Re: Input Type Check
Oh, well then move the Match before and out of the if block, then add a condition for if the match.Value != ""
Code:
Match match = check.Match("[0-9]+");
if (text.Length > 0 && match.Value != "")
{
}
There, that should work, if not, then use some intellisense to find a property to check against in that if block.
-
July 9th, 2009, 10:37 PM
#6
Re: Input Type Check
Code:
private void textBox1_KeyPress( object sender, KeyPressEventArgs e )
{
e.Handled = !( new Regex( "[0-9]+" ).IsMatch( e.KeyChar.ToString( ) ) );
}
-
July 10th, 2009, 08:11 AM
#7
Re: Input Type Check
could also use...
Code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48) || (e.KeyChar > 57))
e.Handled = true;
}
-
July 10th, 2009, 04:48 PM
#8
Re: Input Type Check
Thanks for all your replies / I did think of using a regular expression but thought there might be a better way to do it. It seems this probably is the best way to go about it.
-
July 10th, 2009, 04:54 PM
#9
Re: Input Type Check
I can't think of a better way to parse text than by using a regular expression, even in a simple case like this.
-
July 10th, 2009, 05:51 PM
#10
Re: Input Type Check
and why not to use TryParse?
Code:
int guess;
if(!Int32.TryParse(txtGuess.Text, out guess))
{
// throw an exception here or show a message or do whatever you want to do if not a number
}
win7 x86, VS 2008 & 2010, C++/CLI, C#, .NET 3.5 & 4.0, VB.NET, VBA... WPF is comming
remeber to give feedback  you think my response deserves recognition? perhaps you may want to click the Rate this post link/button and add to my reputation
private lessons are not an option so please don't ask for help in private, I won't replay
if you use Opera and you'd like to have the tab-button functionality for the texteditor take a look at my Opera Tab-UserScirpt; and if you know how to stop firefox from jumping to the next control when you hit tab let me know
-
July 10th, 2009, 06:01 PM
#11
Re: Input Type Check
 Originally Posted by memeloo
and why not to use TryParse?
Code:
int guess;
if(!Int32.TryParse(txtGuess.Text, out guess))
{
// throw an exception here or show a message or do whatever you want to do if not a number
}
I have always found TryParse a bit clunky to use. I would prefer preventing the user from entering invalid data in the first place rather than catching it after the fact and showing an error. I usually show a tooltip after catching the invalid input to explain why it is invalid. This is also what Windows does if you attempt to enter an invalid character in a file name for example.
Also, why would you throw an exception if you are using TryParse? The whole point of using that method is to avoid the exception. If you are just going to throw it anyway you may as well just call int.Parse and not worry about errors.
-
July 10th, 2009, 06:05 PM
#12
Re: Input Type Check
I agree with you @BigEd781 if the input has to follow some pattern, like file names or IPs etc. but if it's a simple number I think regex is overcompicated
win7 x86, VS 2008 & 2010, C++/CLI, C#, .NET 3.5 & 4.0, VB.NET, VBA... WPF is comming
remeber to give feedback  you think my response deserves recognition? perhaps you may want to click the Rate this post link/button and add to my reputation
private lessons are not an option so please don't ask for help in private, I won't replay
if you use Opera and you'd like to have the tab-button functionality for the texteditor take a look at my Opera Tab-UserScirpt; and if you know how to stop firefox from jumping to the next control when you hit tab let me know
-
July 10th, 2009, 06:08 PM
#13
Re: Input Type Check
But the only way to handle it beforehand is to use a regex or check the char value explicitly. I think that the regex is preferable in that case. Besides, regular expressions are so useful that I like to find ways to practice them when I can (as long as they do not make my code an unreadable mess )
-
July 10th, 2009, 06:11 PM
#14
Re: Input Type Check
 Originally Posted by BigEd781
But the only way to handle it beforehand is to use a regex or check the char value explicitly.
do you mean some property in visual studio where you can set a regex directly so that you don't have to write a special function?
win7 x86, VS 2008 & 2010, C++/CLI, C#, .NET 3.5 & 4.0, VB.NET, VBA... WPF is comming
remeber to give feedback  you think my response deserves recognition? perhaps you may want to click the Rate this post link/button and add to my reputation
private lessons are not an option so please don't ask for help in private, I won't replay
if you use Opera and you'd like to have the tab-button functionality for the texteditor take a look at my Opera Tab-UserScirpt; and if you know how to stop firefox from jumping to the next control when you hit tab let me know
-
July 10th, 2009, 06:14 PM
#15
Re: Input Type Check
No, I just mean that, in order to set the "Handled" property you need to figure out whether or not the input char is a number. The only two (reasonable) ways to do that is either with a regex or by check the byte value of the char and making sure that it is in the numerical character range. I would prefer the regex in that case.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|