How do I make a textbox that only accepts numbers?

后端 未结 30 1583
梦如初夏
梦如初夏 2020-11-21 06:05

I have a windows forms app with a textbox control that I want to only accept integer values. In the past I\'ve done this kind of validation by overloading the KeyPress event

30条回答
  •  温柔的废话
    2020-11-21 06:54

    This is exactly what the Validated/Validating events were designed for.

    Here's the MSDN article on the topic: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating.aspx

    The TL;DR version: check the .Text property in the Validating event and set e.Cancel=True when the data is invalid.

    When you set e.Cancel=True, the user can't leave the field, but you will need to give them some kind of feedback that something's wrong. I change the box's background color to light red to indicate a problem. Make sure to set it back to SystemColors.Window when Validating is called with a good value.

提交回复
热议问题