How to check the characters that the user enters in the WinForms text box?

What code should be written to prevent any special characters except "_" (underscore) when entering a name in a text box?

If such a symbol exists, a pop-up message should appear.

-2
c # validation winforms textbox
source share
2 answers

Instead of writing code for you, here are the basic steps necessary to achieve this feat:

  • Access the KeyDown for your TextBox control.

  • Use something like the Char.IsSymbol method to check if the character they typed is allowed. Be sure to explicitly point out the underline because you want to allow it as a special case with other characters.

  • If the correct character is entered, do nothing. WinForms will take care of pasting it into the text box.

    However, if an invalid character is entered, you need to show the user a message telling them that the character is not accepted by the text field. A few things to do here:

    • Set the e.SuppressKeyPress property to true. This will prevent the character from appearing in the text box.

    • Display a popup in the text box indicating that the character entered by the user is not accepted by the text box and tells them which characters are considered valid.
      The easiest way to do this is to use the ToolTip class . Add this control to your form at design time and show it when necessary using one of the Show method overloads. In particular, you will want to use one of the overloads, which allows you to specify IWin32Window to associate a tooltip (this is your control using a text field).

      An example of a balloon-style tooltip, displaying an error message.

      Alternatively, instead of a tooltip, you can display a small error icon next to the text box control, informing the user that their last login is invalid. This is easy to implement with the ErrorProvider control . Add it to your form at design time, just like controlling the tooltip, and call the SetError method at run time to display an error message.

      An example of an ErrorProvider control, set on a text box.

      Whatever you do, do not show the message box! This violates the user trying to enter it, and it is likely that they will inadvertently reject it by entering the next letter that they would like to type.

+14
source share

Add a TextBox KeyDown handler. You can check which key was pressed there and do whatever you want with it, including a popup with a message.

0
source share

All Articles