How do I validate characters a user types into a WinForms textbox?
What code should I write to prevent any special characters except '_' (underscore) whil开发者_JAVA百科e entering the name in text box?
If such character exist then a popup message should appear.
Rather than me writing the code for you, here are the basic steps required for accomplishing such a feat:
Handle the
KeyDown
event for yourTextBox
control.Use something like the
Char.IsSymbol
method to verify whether or not the character that they typed is allowed. Make sure you check explicitly for the underscore, because you want to allow it as a special case of other symbols.If a valid character is typed, do nothing. WinForms will take care of inserting it into the textbox.
However, if an invalid character is typed, you need to show the user a message, informing them that the character is not accepted by the textbox. A couple of things to do here:
Set the
e.SuppressKeyPress
property to True. This will prevent the character from appearing in the textbox.Display a tooltip window on the textbox, indicating that the character the user typed is not accepted by the textbox and informing them what characters are considered valid input.
The easiest way to do this is using theToolTip
class. Add this control to your form at design time, and display it when appropriate using one of the overloads of theShow
method.
In particular, you'll want to use one of the overloads that allows you to specify anIWin32Window
to associate the tooltip with (this is your textbox control).Alternatively, instead of a tooltip, you can display a little error icon next to the textbox control, informing the user that their last input was invalid. This is easy to implement using an
ErrorProvider
control. Add it to your form at design time, just like the tooltip control, and call theSetError
method at run-time to display an error message.Whatever you do, do not display a message box! That disrupts the user trying to type, and it's likely that they'll inadvertently dismiss it by typing the next letter they wanted to type.
Add a handler to the TextBox
's KeyDown
event. You can examine which key was pressed there, and do whatever you want with it, including popping up a message box.
精彩评论