开发者

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:

  1. Handle the KeyDown event for your TextBox control.

  2. 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.

  3. 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:

    1. Set the e.SuppressKeyPress property to True. This will prevent the character from appearing in the textbox.

    2. 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 the ToolTip class. Add this control to your form at design time, and display it when appropriate using one of the overloads of the Show method.
      In particular, you'll want to use one of the overloads that allows you to specify an IWin32Window to associate the tooltip with (this is your textbox control).

      How do I validate characters a user types into a WinForms textbox?

      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 the SetError method at run-time to display an error message.

      How do I validate characters a user types into a WinForms textbox?

      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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜