Restrict numbers and letters in textbox - C#

前端 未结 6 1596
心在旅途
心在旅途 2021-01-24 10:35

I want to restrict what numbers and letters can be entered into a textbox. Let\'s say I only want to allow numbers 0-5 and letters a-d (both lower and uppercase). I already tri

6条回答
  •  日久生厌
    2021-01-24 11:17

    Use the KeyDown event and if the e.Key is not in your allowable set, then just e.Handled = true.

    An alternative would be accept all input, validate it and then provide useful feedback to the user, for example an error label asking them to enter data within a certain range. I prefer this method as the user knows something went wrong and can fix it. It is used throughout the web on web forms and would be not at all surprising for a user of your app. Pressing a key and getting no response at all might be confusing!

    http://en.wikipedia.org/wiki/Principle_of_least_astonishment

提交回复
热议问题