Stop someone from pasting into a TextBox
This article goes hand in hand with my article called "Restrict characters entered into textbox" and I shall use pretty much the same example as I used before.
If you wanted to stop a user from entering anything but numbers into a TextBox you could use the method described in the previous article, but the one problem with that is that the user is still able to paste letters into the TextBox. The following code will not only stop the user from entering anything except for the particular characters specified but also wont allow for the user paste.
As you can see from the code we do the following things;
- We set the TextBox's ContextMenuStrip to a new ContextMenuStrip, what this does it that it stops the menu coming up when the user right clicks within the TextBox, which in turn stops them pressing paste.
- When a key is pressed in the TextBox, we first check to see if the user has pressed Ctrl+V, which is the KeyChar is Chr(22).
- Check to see whether the IndexOf the entered key within the allowedChars String is -1, which means it is not within the String.
- We also allow for the key to be 'Enter' or backspace.
Last Updated (Sunday, 22 August 2010 12:15)


