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:
- 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.
- 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.
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.
25 Feb 2006 : Minor bug fixes.
19 Feb 2006 : Original article submitted.