Allowing Cut & Paste to Occur in a TextBox That Has Code Validation

Joined
Sep 3, 2008
Messages
19
Programming Experience
1-3
I created a form which consists of many textboxes. One of these textboxes allow the user to enter the telephone number using only numbers 0-9. I had written code in the key press event for this textbox which looks at the ascii code for the key pressed by the user while entering the characters in the telephone textbox. If the key pressed has an ascii value that lies within the range of ascii values for digits 0 to 9, nothing is done, otherwise the program will set e.handled to true for other characters that don't fall within the ascii range. I found when I copy a telephone number from a webpage and try to paste it to the telephone textbox, the program doesn't allow me to paste any characters into the telephone textbox. How can I overcome this problem? That is, I would like to be able to paste a telephone number into the telephone textbox and have the code in the key press event to check each one of the characters pasted into the telephone textbox. This also happens when I copy and paste a telephone # from a Word document into the telephone textbox.




Thanks.
 
Use a MaskedTextBox for this. Set it to allow only the 9 digits and it'll handle the paste stuff for you
 
Initially, I did use a mask edit textbox and set the mask to (###)###-####. I even tried the mask ##########. When the user didn't enter anything for this textbox, it returned ( )___-____ or _____________ depending on the mask. If I use the mask edit textbox, how can I get it to return a blank instead of ( )___-____ or __________ when I want to save its value into a database. I don't want to write more code to check the characters in this ( )___-____ or _____________ string for blank characters.
 
Initially, I did use a mask edit textbox and set the mask to (###)###-####. I even tried the mask ##########. When the user didn't enter anything for this textbox, it returned ( )___-____ or _____________ depending on the mask. If I use the mask edit textbox, how can I get it to return a blank instead of ( )___-____ or __________ when I want to save its value into a database. I don't want to write more code to check the characters in this ( )___-____ or _____________ string for blank characters.
MTB.Mask = "(000) 000-0000"
MTB.PromptChar = "#"
MTB.TextMaskFormat = MaskFormat.IncludeLiterals

That will tell the MTB to include the ()'s but not the PromptChar itself (_ or # according to your other post)
 
Back
Top