CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15
  1. #1
    Join Date
    Dec 2005
    Location
    Waterloo ON
    Posts
    545

    Only accept number in textbox

    I just figured it out. Now post the source code here and hope anybody help me test it. Want it be perfect.

    Thanks a lot.
    Code:
    int iCaret = 0;
    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        TextBox txt = (TextBox)sender;
    
        switch (e.KeyCode)
        {
            case Keys.Left:
                iCaret = ((iCaret - 1) < 0) ? 0 : (iCaret - 1);
                break;
            case Keys.Right:
                iCaret = ((iCaret + 1) > txt.Text.Length) ? txt.Text.Length : (iCaret + 1);
                break;
            case Keys.Home:
                iCaret = 0;
                break;
            case Keys.End:
                iCaret = txt.Text.Length;
                break;
            case Keys.Back:
                iCaret = ((iCaret - 1) < 0) ? 0 : (iCaret - 1);
                break;
            default:
                break;
        }
    }
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        TextBox txt = (TextBox)sender;
    
        if (e.KeyChar != 8 && iCaret == 0 && txt.Text.Contains("-"))
        {
            e.Handled = true;
            return;
        }
        if (char.IsDigit(e.KeyChar) || e.KeyChar == 8)
            e.Handled = false;
        else
        {
            if (e.KeyChar == '-')
            {
                if (!txt.Text.Contains("-"))
                {
                    txt.Text = "-" + txt.Text;
                    iCaret++;
                    txt.Select(iCaret, 0);
                }
                e.Handled = true;
            }
            else if (e.KeyChar == '.')
            {
                e.Handled = txt.Text.Contains(".");
            }
            else
                e.Handled = true;
        }
    
        if (!e.Handled && e.KeyChar != 8)
            iCaret++;
    }
    The difficulty is that you have no idea how difficult it is.

    .Net 3.5/VS 2008

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

    Re: Only accept number in textbox

    I would recommend using a regular expression. Much shorter and cleaner.

    http://www.codeguru.com/forum/showth...66#post1792166

  3. #3
    Join Date
    Dec 2005
    Location
    Waterloo ON
    Posts
    545

    Re: Only accept number in textbox

    Quote Originally Posted by BigEd781 View Post
    I would recommend using a regular expression. Much shorter and cleaner.

    http://www.codeguru.com/forum/showth...66#post1792166
    I tried that way, but I failed to type in minus number.

    Thanks.
    The difficulty is that you have no idea how difficult it is.

    .Net 3.5/VS 2008

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

    Re: Only accept number in textbox

    Quote Originally Posted by jasonli View Post
    I tried that way, but I failed to type in minus number.

    Thanks.
    That just means that your RegEx is incorrect. That switch statement is hard to understand, but a simple RegEx is a one liner and most will know immediately what you are trying to do.

  5. #5
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Only accept number in textbox

    Any reason you can't just set the style on the textbox to only accept numbers?

  6. #6
    Join Date
    Dec 2005
    Location
    Waterloo ON
    Posts
    545

    Re: Only accept number in textbox

    Quote Originally Posted by BigEd781 View Post
    That just means that your RegEx is incorrect. That switch statement is hard to understand, but a simple RegEx is a one liner and most will know immediately what you are trying to do.
    I searched a lot for regular expression and finally got "^[+-]?\d+\.?\d*$", which can validate mostly, not completely. I put validation in KeyPress event because I don't wanna show invalid character in textbox.

    any idea?

    Quote Originally Posted by Arjay View Post
    Any reason you can't just set the style on the textbox to only accept numbers?
    I did not find any property about this for textbox in Windows form. Thank you anyway.
    The difficulty is that you have no idea how difficult it is.

    .Net 3.5/VS 2008

  7. #7
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: Only accept number in textbox

    I have always found it easier to use a numericUpDown control. After all this can also act as a text box control. Just set the some properties properly and there you go. Without writing any code, you have a numeric textbox.

    Also take a look at this article on MSDN
    http://msdn.microsoft.com/en-us/library/ms229644.aspx

  8. #8
    Join Date
    Dec 2005
    Location
    Waterloo ON
    Posts
    545

    Re: Only accept number in textbox

    Quote Originally Posted by Shuja Ali View Post
    I have always found it easier to use a numericUpDown control. After all this can also act as a text box control. Just set the some properties properly and there you go. Without writing any code, you have a numeric textbox.

    Also take a look at this article on MSDN
    http://msdn.microsoft.com/en-us/library/ms229644.aspx
    NumericTextBox is a very nice class. I did not try this yet. I'm just wondering what will happen if user inputs "87432.-90". I am gonna try this.

    Thanks.
    The difficulty is that you have no idea how difficult it is.

    .Net 3.5/VS 2008

  9. #9
    Join Date
    Mar 2005
    Location
    Vienna, Austria
    Posts
    4,538

    Re: Only accept number in textbox

    Why not simple use a filter so only numbers can reach the textbox.
    You can do it in the keydown event delegate of your texboxes like
    Code:
    public void TextBox1_ KeyDown(KeyEventArgs e) {
    MathSignsOnly(e); 
    }
    private void MathSignsOnly(KeyEventArgs e) {
        if (!((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9 && !e.Shift) || (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
            e.KeyCode == Keys.Oemcomma || e.KeyCode == Keys.OemPeriod || e.KeyCode == Keys.Back || e.KeyCode == Keys.Decimal || e.KeyCode == Keys.Delete ||
            e.KeyCode == Keys.Enter || e.KeyCode == Keys.Escape || e.KeyCode == Keys.NumLock || e.KeyCode == Keys.Right ||
            e.KeyCode == Keys.Left || e.KeyCode == Keys.Home || e.KeyCode == Keys.End)) {
            e.SuppressKeyPress = true;
        }
    }
    I'm using such filters together with a decorator. This way I can have different filters for different textboxes. They all get exactly that filter they need.
    The above filter allowes unsigned decimal values only but no alphabet letters. This way you can supress everything you want if you want a minus sign simple add it here. If you want keyUp KeyDown, Left, right simple add them to be allowed
    Last edited by JonnyPoet; February 26th, 2009 at 03:59 PM.
    Jonny Poet

    To be Alive is depending on the willingsness to help others and also to permit others to help you. So lets be alive. !
    Using Code Tags makes the difference: Code is easier to read, so its easier to help. Do it like this: [CODE] Put Your Code here [/code]
    If anyone felt he has got help, show it in rating the post.
    Also dont forget to set a post which is fully answered to 'resolved'. For more details look to FAQ's about Forum Usage. BTW I'm using Framework 3.5 and you ?
    My latest articles :
    Creating a Dockable Panel-Controlmanager Using C#, Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7

  10. #10
    Join Date
    Dec 2005
    Location
    Waterloo ON
    Posts
    545

    Re: Only accept number in textbox

    Quote Originally Posted by JonnyPoet View Post
    Why not simple use a filter so only numbers can reach the textbox.
    You can do it in the keydown event delegate of your texboxes like
    Code:
    public void TextBox1_ KeyDown(KeyEventArgs e) {
    MathSignsOnly(e); 
    }
    private void MathSignsOnly(KeyEventArgs e) {
        if (!((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9 && !e.Shift) || (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
            e.KeyCode == Keys.Oemcomma || e.KeyCode == Keys.OemPeriod || e.KeyCode == Keys.Back || e.KeyCode == Keys.Decimal || e.KeyCode == Keys.Delete ||
            e.KeyCode == Keys.Enter || e.KeyCode == Keys.Escape || e.KeyCode == Keys.NumLock || e.KeyCode == Keys.Right ||
            e.KeyCode == Keys.Left || e.KeyCode == Keys.Home || e.KeyCode == Keys.End)) {
            e.SuppressKeyPress = true;
        }
    }
    I'm using such filters together with a decorator. This way I can have different filters for different textboxes. They all get exactly that filter they need.
    The above filter allowes unsigned decimal values only but no alphabet letters. This way you can supress everything you want if you want a minus sign simple add it here. If you want keyUp KeyDown, Left, right simple add them to be allowed
    Almost perfect one! It can't prevent user typing "459.54-98".
    I added lots of source code to prevent this.

    Thank you.
    The difficulty is that you have no idea how difficult it is.

    .Net 3.5/VS 2008

  11. #11
    Join Date
    Mar 2005
    Location
    Vienna, Austria
    Posts
    4,538

    Re: Only accept number in textbox

    Quote Originally Posted by jasonli View Post
    Almost perfect one! It can't prevent user typing "459.54-98".
    I added lots of source code to prevent this.

    Thank you.
    This needs to be handled in the decorator Formatting method which simple checks the mathematical value of the textbox and if a minus is contained in the input its always formatted to the beginning of the value so it never could be set to the end of a value.
    Simple but effective.
    Are you already done with your code or have you still troubles ?
    If so I would extract the code of my dll for this one method and zip an example for you. If you are already done, I wouldn't do as its per sure an hour of work to copy it to an demo-project and looking if all neded methods are included. Its not much code, but the work is to only copy that part which is used for one textbox and uses the IDecimalUnsigned Interface which I have designed for that. Because having different formatts needed in any program I have designed a family of such decorators so I only need to use the correct one for a given purpose and this way all my textboxes are protected against wrong input.
    The advantage of this is that you are pressing a key and it instantly reacts while validation normally works after you have finished input.
    So when I type 123- then it does 123 and when I type the minus it instantly writes -123 Whats about 123.01.01 is your code also disallowing wrong input like this ?
    Jonny Poet

    To be Alive is depending on the willingsness to help others and also to permit others to help you. So lets be alive. !
    Using Code Tags makes the difference: Code is easier to read, so its easier to help. Do it like this: [CODE] Put Your Code here [/code]
    If anyone felt he has got help, show it in rating the post.
    Also dont forget to set a post which is fully answered to 'resolved'. For more details look to FAQ's about Forum Usage. BTW I'm using Framework 3.5 and you ?
    My latest articles :
    Creating a Dockable Panel-Controlmanager Using C#, Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7

  12. #12
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104

    Re: Only accept number in textbox

    Really, it's like Shuja said; use a numericupdown control. If you need to screw in a screw, use a screwdriver, not a chisel, hammer, knife etc..
    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  13. #13
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104

    Re: Only accept number in textbox

    Quote Originally Posted by jasonli View Post
    I'm just wondering what will happen if user inputs "87432.-90".
    In an NUD? nothing. It wont work
    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  14. #14
    Join Date
    Mar 2005
    Location
    Vienna, Austria
    Posts
    4,538

    Re: Only accept number in textbox

    Quote Originally Posted by cjard View Post
    In an NUD? nothing. It wont work
    Simple try it. Set maimum and minimum Range as you need it, set DecimalPlaces to your needs e.g '2' and Increment to 0.01

    Then test it if this does what you want. If you do a wrong input like "12.98-98" the input will vanish as soon as you click to the next field because its validated obviously when leaving it. But Clicking to a toolstrip Button does nothing, there is still the wrong value there and numericUpDown1. Value is Zero

    I dont know if that fits your needs for me this wasn't acceptable as in programs working with finances a wrong input needs an errorindication so it couldn't be overlooked that there was a typo which killed my input. ( I dont think the user intentionally puts in wrong data but when I look to our 10 finger typing secretary girls they type and type and sometimes their fingers slip a bit and the Enter key was missed and the input of two fields is now in one. In this case they get a red asterix to the wrong input fields.

    But just about the theme of whats the best way of error prevention and errorhandling and the best way of input validation you can fill books IMHO
    Jonny Poet

    To be Alive is depending on the willingsness to help others and also to permit others to help you. So lets be alive. !
    Using Code Tags makes the difference: Code is easier to read, so its easier to help. Do it like this: [CODE] Put Your Code here [/code]
    If anyone felt he has got help, show it in rating the post.
    Also dont forget to set a post which is fully answered to 'resolved'. For more details look to FAQ's about Forum Usage. BTW I'm using Framework 3.5 and you ?
    My latest articles :
    Creating a Dockable Panel-Controlmanager Using C#, Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7

  15. #15
    Join Date
    Dec 2005
    Location
    Waterloo ON
    Posts
    545

    Re: Only accept number in textbox

    I really appreciate you guy's inputs. Even though I don't get the better solution, I have learnt a lot from you guys. Thank you very much.

    Like cjard said, I used a knife to screw in a screw. Anyway, my code is working. I am gonna use it until better one comes out.

    JonnyPoet, thank you for your offer. For now I don't have trouble to implement the function, so you don't need to waste time copying codes on this.

    Finally, I just wanna say, "no coding, no function." You can't have everything done by only setting some properties.

    Thank you guys again! Happy coding!
    The difficulty is that you have no idea how difficult it is.

    .Net 3.5/VS 2008

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