Reputation: 12341
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 to 5, so no negative and no decimal as any value higher crashes the app. Thank you!
Upvotes: 0
Views: 845
Reputation: 13507
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.
Upvotes: 2
Reputation: 8967
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).
Upvotes: 1