CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    Join Date
    Dec 2008
    Posts
    87

    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

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    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.

  3. #3
    Join Date
    May 2006
    Posts
    306

    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.

  4. #4
    Join Date
    Nov 2007
    Location
    .NET 3.5 / VS2008 Developer
    Posts
    624

    Re: Input Type Check

    Quote Originally Posted by code? View Post
    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.

  5. #5
    Join Date
    May 2006
    Posts
    306

    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.

  6. #6
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Input Type Check

    Code:
            private void textBox1_KeyPress( object sender, KeyPressEventArgs e )
            {
                e.Handled = !( new Regex( "[0-9]+" ).IsMatch( e.KeyChar.ToString( ) ) );
            }

  7. #7
    Join Date
    Nov 2007
    Location
    .NET 3.5 / VS2008 Developer
    Posts
    624

    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;
    }

  8. #8
    Join Date
    Dec 2008
    Posts
    87

    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.

  9. #9
    Join Date
    Jun 2008
    Posts
    2,477

    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.

  10. #10
    Join Date
    Oct 2008
    Location
    Cologne, Germany
    Posts
    756

    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

  11. #11
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Input Type Check

    Quote Originally Posted by memeloo View Post
    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.

  12. #12
    Join Date
    Oct 2008
    Location
    Cologne, Germany
    Posts
    756

    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

  13. #13
    Join Date
    Jun 2008
    Posts
    2,477

    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 )

  14. #14
    Join Date
    Oct 2008
    Location
    Cologne, Germany
    Posts
    756

    Re: Input Type Check

    Quote Originally Posted by BigEd781 View Post
    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

  15. #15
    Join Date
    Jun 2008
    Posts
    2,477

    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.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured