CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 23
  1. #1
    Join Date
    Dec 2009
    Location
    Kathmandu,Nepal
    Posts
    168

    Numbers Only Textboxes!!

    Hi! every one.
    This time I have a problem on working with textboxes. What I have is 2 textboxes 1 for input of first integer type number(say a1) and and second for input of second is integer type number (say b1)...now I want to make sure that user can only type numbers in it.....
    I have done some homework of my own but it does not check the space character and this method does not allow the use of tabs for shifting through the textboxes.......
    Please Guide me in Here....Some hints for some would also be welcomed........

  2. #2
    Join Date
    May 2007
    Location
    Denmark
    Posts
    623

    Re: Numbers Only Textboxes!!

    I can't remember where I originally got this, but it might be close to what you need:

    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows.Forms;
    using System.Globalization;
    
    namespace Namespace
    {
        public class NumericTextBox : TextBox
        {
            bool allowSpace = false;
    
            // Restricts the entry of characters to digits (including hex), the negative sign,
            // the decimal point, and editing keystrokes (backspace).
            protected override void OnKeyPress(KeyPressEventArgs e)
            {
                base.OnKeyPress(e);
    
                NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
                string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
                string groupSeparator = numberFormatInfo.NumberGroupSeparator;
                string negativeSign = numberFormatInfo.NegativeSign;
    
                string keyInput = e.KeyChar.ToString();
    
                if (Char.IsDigit(e.KeyChar))
                {
                    // Digits are OK
                }
                else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) ||
                 keyInput.Equals(negativeSign))
                {
                    // Decimal separator is OK
                }
                else if (e.KeyChar == '\b')
                {
                    // Backspace key is OK
                }
                //    else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
                //    {
                //     // Let the edit control handle control and alt key combinations
                //    }
                else if (this.allowSpace && e.KeyChar == ' ')
                {
    
                }
                else
                {
                    // Consume this invalid key and beep
                    e.Handled = true;
                    //    MessageBeep();
                }
            }
    
            public int IntValue
            {
                get
                {
                    return Int32.Parse(this.Text);
                }
            }
    
            public decimal DecimalValue
            {
                get
                {
                    return Decimal.Parse(this.Text);
                }
            }
    
            public bool AllowSpace
            {
                set
                {
                    this.allowSpace = value;
                }
    
                get
                {
                    return this.allowSpace;
                }
            }
        }
    
    }
    It's not a bug, it's a feature!

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

    Re: Numbers Only Textboxes!!

    Quote Originally Posted by rocky_upadhaya View Post
    this method does not allow the use of tabs for shifting through the textboxes
    what kind of method?

    have you tried to catch the KeyDown event?
    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

  4. #4
    Join Date
    Dec 2009
    Location
    Kathmandu,Nepal
    Posts
    168

    Re: Numbers Only Textboxes!!

    I will look into the method that memelo gave...but for now I have somewhat a solution in this

    Code:
    try
    {
      
      if(Convert.ToInt32(a1.Text)==5)
     //code
     if(Convert.ToInt32(b1.Text)==6)
     //code
    }
    catch(FormatException)
    {
    }
    but can I know exactly which which statement generated the exception??

  5. #5
    Join Date
    Nov 2002
    Location
    .NET 3.5 VS2008
    Posts
    1,039

    Re: Numbers Only Textboxes!!

    Quote Originally Posted by rocky_upadhaya View Post
    I will look into the method that memelo gave...but for now I have somewhat a solution in this

    Code:
    try
    {
      
      if(Convert.ToInt32(a1.Text)==5)
     //code
     if(Convert.ToInt32(b1.Text)==6)
     //code
    }
    catch(FormatException)
    {
    }
    but can I know exactly which which statement generated the exception??
    Uhm...I don't think this a good solution to your problem. Why don't use the NumericTextBox that 'Foamy' posted? If you don't want to create a new control perhaps you can use a regular expression validator? That way the user get's some feedback and you wont' have to worry about invalid values...

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

    Re: Numbers Only Textboxes!!

    actually you should use the code @foamy posted. it exacly what you're looking for.

    @foamy: I didn't know that the Char class has so cool methods like IsDigit. thx for posting it.
    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

  7. #7
    Join Date
    Dec 2009
    Location
    Kathmandu,Nepal
    Posts
    168

    Re: Numbers Only Textboxes!!

    Thanks for the suggestion fells...now i will surely use the code example posted by the foamy...but I am not sure it will support tab to move through the textboxes.....but if it is possible I will update my work and its result....Thank you guys........

  8. #8
    Join Date
    Jun 2001
    Location
    Melbourne/Aus (C# .Net 4.0)
    Posts
    686

    Re: Numbers Only Textboxes!!

    Alternatively, let them type anything they want but then validate it, either as textbox loses focus (can be painful) or when they clikc [OK] on the form (assuming that is an option).
    Rob
    -
    Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......

  9. #9
    Join Date
    Dec 2009
    Location
    Kathmandu,Nepal
    Posts
    168

    Re: Numbers Only Textboxes!!

    any example or little insight on that? so that i can compare both the methode and evaluate which one suites me...coz i dont want to loose tab key navigation through textboxes...thanks

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

    Re: Numbers Only Textboxes!!

    Code:
    private void textBox1_KeyPress( object sender, KeyPressEventArgs e )
    {
        if( e.KeyChar == (char)Keys.Tab ) return;
        e.Handled = !Char.IsDigit( e.KeyChar );
    }
    That is obviously a contrived example, it just shows how to keep tab working.

  11. #11
    Join Date
    Nov 2002
    Location
    .NET 3.5 VS2008
    Posts
    1,039

    Re: Numbers Only Textboxes!!

    Quote Originally Posted by rliq View Post
    Alternatively, let them type anything they want but then validate it, either as textbox loses focus (can be painful) or when they clikc [OK] on the form (assuming that is an option).
    A good suggestion. I would go for this option unless there was a specific requirement to validate as the data in entered.

    rliq: I've just noticed .NET 4 in your location. how are you finding .NET 4? Are you using VS2010 or you just using the SDK? What about the new language features?

  12. #12
    Join Date
    May 2007
    Location
    Denmark
    Posts
    623

    Re: Numbers Only Textboxes!!

    Um, tabbing works fine with the control I posted
    (Just tested it to make sure)

    Glad everyone likes it - I just wish the original author had put his/her name in the comments :-P
    It's not a bug, it's a feature!

  13. #13
    Join Date
    Jun 2001
    Location
    Melbourne/Aus (C# .Net 4.0)
    Posts
    686

    Re: Numbers Only Textboxes!!

    if you validate it at the 'end', when the user clicks [OK] you won't lose the tab functionality. Is there some reason why you have to evaluate after each character is typed, as that can start to complicate your code.
    Rob
    -
    Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......

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

    Re: Numbers Only Textboxes!!

    Quote Originally Posted by rliq View Post
    if you validate it at the 'end', when the user clicks [OK] you won't lose the tab functionality. Is there some reason why you have to evaluate after each character is typed, as that can start to complicate your code.
    Why let users enter bad data to begin with? It is just annoying, and it is trivial to pass the Tab messages through the control. I would ask why anyone *would* validate at the end instead of up front.

  15. #15
    Join Date
    Dec 2009
    Location
    Kathmandu,Nepal
    Posts
    168

    Re: Numbers Only Textboxes!!

    I am extreamly sorry for not mentioning that I was working on WPF and is the code given by foamy is not valid for WPF Applications?? because if comes with
    Code:
    Error	1	The type or namespace name 'KeyPressEventArgs' could not be found (are you missing
    a using directive or an assembly reference?)
    I am again sorry for my mistake...anyway this thread would help other guys......and I urge Moderators of this site to change shift this thread to WPF section.......

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