Click here to Skip to main content
Click here to Skip to main content

Numeric TextBox

By , 1 Apr 2006
 

Sample Image - NumericTextBox.gif

Introduction

Many of us have faced a situation where we want the user to enter a number (an integer or a double) in a TextBox, thus seeking a way to prevent him from inserting invalid characters. Almost all of the available solutions required to use a custom control inherited from TextBox control. Regarding the fact that the developers sometimes (or perhaps often!) decide to add this facility to their TextBoxes after they have added several TextBox controls, and added many other lines of code to their project based on these controls names, these solutions are practically of limited use. (The programmer needs to remove all TextBoxes, add the new custom control instead of each of them, and make all the required changes to the code.)

Considering that, I broke the project to two blocks:

  1. To validate each character a user presses on the keyboard, check if its addition to the current value of the TextBox will still result in a numeric value, and prevent the character to be added to the TextBox value if the answer is no.
  2. To perform the validation on pasting into the TextBox. Pasting could be done through pressing CTRL+V, SHIFT+INSERT or using the right-click context menu.

The first issue can be handled using the onKeyPress event of the TextBox. For the second part, unfortunately, we don't have an onPaste event. I used a brilliant method dedicated in this Experts-Exchange thread.

Using the code

You will need to set the numericTextboxKeyPress sub to handle the onKeyPress event for all TextBoxes you want to validate. This will handle the input characters as the user types them.

The creative TextBoxOnChange class handles the paste event for the TextBoxes. For each TextBox on which you want to handle the paste event, you should add a line of code like this:

//Example of adding an onPaste handler
Dim onPaste1 As New TextBoxOnPaste(Me.TextBox1)

I added two checkboxes to the demo project source code to facilitate your learning how to use the code for multiple checkboxes.

History

25 Feb 2006 : Minor bug fixes.

19 Feb 2006 : Original article submitted.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Hojjat Salmasian
Web Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionAdvanced NumericmemberSureshjv11 Dec '12 - 19:54 
Laugh | :laugh:
Hey
You can check here Advanced Numeric Text Box
http://getvbnetcode.blogspot.in/

QuestionHey You can check here Advanced Numeric Text Box http://getvbnetcode.blogspot.in/memberSureshjv11 Dec '12 - 19:53 
Hey
You can check here Advanced Numeric Text Box
http://getvbnetcode.blogspot.in/

GeneralPasted datamemberiamthecodecutter8 May '11 - 19:26 
Thanks for the code, works a treat Smile | :)
 
But it now will not allow me to paste data into that textbox. I would like to maintain the same rules but paste information into the textbox, any ideas ... ANYONE.... Please Cry | :((
GeneralMy vote of 1membersaeed mousavi4 Feb '09 - 4:54 
not really functional
GeneralCool and what about positive numbersmemberSalarSoft11 Jul '07 - 20:07 
Very useful and errorless
 
Can you add limitation for positive numbers? it's can be a useful feature.
 
thanksSmile | :)

Generaldecimal pointmembertorbero11 Jul '07 - 8:30 
Is your code very useful, but is it necessary to control that alone a decimal point is introduced 23.3443 and not 23.34.43 like one can make it?
 
greetings
GeneralRe: decimal pointmemberHojjat Salmasian12 Jul '07 - 4:16 
Well I thought that way. However, you may want to change the code to meet your needs. Smile | :)
GeneralSmall IssuememberMNC6217 Jun '07 - 21:26 
Thanks for this, very useful but I have a smallish issue.
 
The example from the downloaded project does not allow you to enter a decimal the format like .xx but instead 0.xx. Small point I know but many users will input a fraction this way when entering large volumes od data.Smile | :)
GeneralFlaw....memberchris1759 Feb '07 - 7:31 
Did you know you can do the following.....
1. Press the 2 number key.
2. Open notepad and press the - key.
3. Copy the "-" text into the clipboard.
4. Past the "-" text just after the 2 in the number edit box...
 
Chris
GeneralRe: Flaw....memberHojjat Salmasian9 Feb '07 - 9:58 
Thanks for notifying. I'm not actively following this project, but I will try to upload an update as soon as I can... by the way, did you find a solution to it yourself?
GeneralThank youmemberPocketJem5 Dec '06 - 9:49 
As a newbie to VB.net can I just say a BIG thank you for this code. It does exactly what I need.
 
I had attempted to write a similar routine but mine had loads of code and didn't work very well Frown | :-(
 
I now understand how it can be done much better and simpler by taking a completely different approach.
 
Thank you so much.
 
Jem
GeneralRe: Thank youmemberHojjat Salmasian5 Dec '06 - 19:06 
Thanks for the complements. I'm glad I've helped you.
 
Hojjat
GeneralRe: Thank youmemberPocketJem6 Dec '06 - 8:35 
Hi Hojjat
 
I have a question...
 
I would like to use this code on a program that has quite a few different forms. On each form there are multiple textboxes, one of the forms has 12 textboxes all requiring the same numeric validation.
 
Would it be possible to have this code apply globally to all the textboxes on the form rather than having to list each one separately in the sub header?
 
If so how could I do this.
 
Even better would be to put the code into a module and have it apply to ALL textboxes in my program as none of them require anything other than numeric input.
 
Thank you for any help or advice you can give me.
 
Cheers
 
Jem
GeneralRe: Thank youmemberHojjat Salmasian7 Dec '06 - 6:58 
As I said before, my solution is for use when programmers decide to add this facility to their TextBoxes after they have added several TextBox controls, and added many other lines of code to their project based on these controls names.
However, if you are at the beginning of the design of your forms, it is more appropriate to use a user control which is a textbox accepting numeric values, rather than using the normal textbox control and adding the feature to it as I do in this article.
You can find such controls by searching in the internet, and even in the same codeproject web site:
http://www.codeproject.com/cs/miscctrl/HDNumericTextBox.asp
http://www.codeproject.com/vb/net/2gs_txtbx.asp
GeneralThe contorl don't support inputing minus symbol.memberzxp31922 Feb '06 - 20:46 
There are some errors when I input minus or paste a string including minus symbol, for example, I can paste "123-456-789" into the control.
GeneralRe: The contorl don't support inputing minus symbol.memberHojjat Salmasian23 Feb '06 - 4:35 
I will fix it as soon as I can.
GeneralRe: The contorl don't support inputing minus symbol.memberRay Cassick25 Feb '06 - 11:22 
But I thought this control was only representing NUMERIC entries.
 
That kind of number, although made up of numeric symbols is not really a number.
 
That entry is more akin to needing something like a masked edit control.
 

My Blog[^]
FFRF[^]


 
-- modified at 17:22 Saturday 25th February, 2006
GeneralRe: The contorl don't support inputing minus symbol.memberHojjat Salmasian26 Feb '06 - 6:31 
>> That kind of number, although made up of numeric symbols is not really a number.
I'm not sure what you mean by the above statement. Afterall, TextBox.Text is always a string, and what I offer here, is to limit this string to contain numeric values only.
GeneralRe: The contorl don't support inputing minus symbol.memberRay Cassick26 Feb '06 - 7:12 
If the aim of your text box is to allow only numeric values only then you have to consider exactly what IS a number.
 
For example:
 
$4.00 is a number
50% is a number
2 is a number
5:00pm could also be considered a number
 
All these above examples are 'numbers' because they represent a numeric AMOUNT type of a construct.
 
The example that the other person gave of '123-456-789' really does not represent a numeric amount, it represents a pattern of characters that just in this case happen to all be characters that are allowed in numeric display.
 
Maybe I am over thinking this a bit, and if I am I am sorry to muddy the discussion here, but I think if your controls focus is to only allow numeric values then you have to consider what really IS a numeric value. Not just the individual characters but what they represent as a whole when entered in. This has a larger meaning than just creating a control that only allows numeric type characters in.
 
If you are only allowing numeric type characters then you have to take into account ALL the different numeric characters and I am not that sure of the overall usefulness of the control at that point.
 
As one further example... IPV4 addresses allow for 4 groups of numbers, each separated by a '.'. Each characters is considered a numeric type character but as whole and IP address is not considered a numeric value. Should your control allow and validate this as a proper value? If it does then it has moved from being a numeric value text box into the realm of an IP address text box.
 
Just trying to push home the fact that once you widen the scope of your control very wide then you open yourself up to tons of problems. If a person wants to enter in an IP address then they should use a control specifically for that type of entry. If a person wants to enter a numeric value (dollars, pounds, percents, etc...) then they use yours here. If they want to end in something else then maybe they use another. Just trying to say that you need to keep your scope on point here and be ready and willing to tell people requesting features and pointing out what 'they' think are bugs, that their request doe snot fit the scope of your control and for what reasons you feel that way. This is one reason why there are so many controls out there that end up no good. They try to be all things to all people and in the end never do anything very well.
 

 

My Blog[^]
FFRF[^]


 
-- modified at 13:19 Sunday 26th February, 2006
GeneralRe: The contorl don't support inputing minus symbol.memberHojjat Salmasian27 Feb '06 - 6:46 
Well in a mathematical point of view (as far as I know), $4.00 is not a number, but a number and a symbol to its left! Wink | ;) Or an IP address is not "a" number, but a set of "four" numbers separated by a decimal sign.
However, in order to make sure such confusion is not going to happen again, I'm modifying the text of article to clearly define what the textboxes are going to do.
I hope my article to be a good start point for others to create their own controls meeting their specific needs.
Thanks for your attention
GeneralRe: The contorl don't support inputing minus symbol.memberLovinBill12 Jul '06 - 23:56 
Just to add my 2 penneth worth....
 
$4.00 isnt a number its an amount of currency. 4.00 is the numeric part
 
Good code piece, perhaps it would be an idea to create a currencyTextBox, percentageTextBox etc??
 
Anyways, thanks for the code..
GeneralRe: The contorl don't support inputing minus symbol.memberHojjat Salmasian15 Jul '06 - 4:06 
That is a point of view too. Smile | :) Thanks for your complements. I think those kinds of textboxes are made by other people before as seperate user controls. There are numeric textbox user controls doing what I offered here too. What I meant to offer here, was a way to prevent using a user control.
Questionvs2005 only?memberGaryMinor222 Feb '06 - 10:31 
The source solution won't open in vs2003.
 

 
Gary Minor
AnswerRe: vs2005 only?memberChristian Graus22 Feb '06 - 10:54 
VS2005 solutions won't open in 2003. You may still be able to use the classes tho.

 
Christian Graus - Microsoft MVP - C++
AnswerRe: vs2005 only?memberHojjat Salmasian22 Feb '06 - 16:08 
Exactly. I wrote the code in VB2005 but the class can be used in VS2003 as well. It uses features available in .NET framework 1.0
I'm aware of no 2005 to 2003 convertor, or I'd post a link to it here.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 1 Apr 2006
Article Copyright 2006 by Hojjat Salmasian
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid