开发者

How can I create a Textbox which only accepts certain integer values?

I've searched the web and was unable to find what I am looking for. I'm using VS2010 and trying to make a w7p app. I'm trying to make a textbox that only accepts a single integer value from 0 开发者_StackOverflow社区to 5, so no negative and no decimal as any value higher crashes the app. Thank you!


Use a NumericUpDown control, if there is one and you can just set the Minimum and Maximum properties.

If there's not, use this in the KeyDown event of the textbox:

List<Keys> allowedKeys = new List<Keys>()
{
    Keys.Back, Keys.D0, Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5,
    Keys.NumPad0, Keys.NumPad1, Keys.NumPad2, Keys.NumPad3, Keys.NumPad4, Keys.NumPad5
};

e.SuppressKeyPress = !allowedKeys.Contains(e.KeyCode);

This will suppress anything that is not a 0-5 or BACKSPACE key. Also, set your Maximum Length property to 1, it will allow only 0 through 5.


Capture the change event of the textbox and check its value using regex (or parse it as an integer and compare it with you range).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜