What is the best way to block certain input keys from being used in a TextBox with out blocking special keystrokes such as Ctrl-V/Ctrl-C?
For example, only allowing the user to enter a subset of characters or numerics such as A or B or C and nothing else.
I would use the keydown-event and use the e.cancel to stop the key if the key is not allowed. If I want to do it on multiple places then I would make a user control that inherits a textbox and then add a property AllowedChars or DisallowedChars that handle it for me. I have a couple of variants laying around that I use for time to time, some allowing money-formatting and input, some for time editing and so on.
The good thing to do it as a user control is that you can add to it and make it to your own killer-text-box. ;)
I used the Masked Textbox control for winforms. There's a longer explanation about it here. Essentially, it disallows input that doesn't match the criteria for the field. If you didn't want people to type in anything but numbers, it simply would not allow them to type anything but numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With