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!
-
3atleyhunter.com/2010/11/12/…Mitch Wheat– Mitch Wheat2011-07-17 01:11:35 +00:00Commented Jul 17, 2011 at 1:11
-
i found this on my own but i need to restrict it to a single int value, so the only accpeted values would be {0,1,2,3,4,5} , so that 10 wont workpyCthon– pyCthon2011-07-17 01:31:57 +00:00Commented Jul 17, 2011 at 1:31
-
pity you didn't mention that in your question...Mitch Wheat– Mitch Wheat2011-07-17 01:32:56 +00:00Commented Jul 17, 2011 at 1:32
Add a comment
|
2 Answers
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.
Comments
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).
6 Comments
MK.
regexp for this is a bad idea
ChrisWue
@Sylverdrag: I guess the phone has limited resources in memory and CPU cycles so you don't want to fire a regex at it on every keypress.
Sylver
@ChrisWue: I am not sure how much resources it would use, but assuming it's too much, that makes sense.
MK.
@Selverdrag just an overkill all around. You almost never really need a regexp for anything, especially something as simple as checking a number range.
Sylver
@MK: Sure. "Regex.Match("[0-5]").Success" is such an overkill, not to mention unreadable and hard to understand compared to a simple solution like restricting the keys and capturing only the keys you want. I can understand that on mobile, resources are scarce and going for other solutions might be justified (I don't know how much overhead is required by the Regex library). On desktop however, that overhead is insignificant and Regex can simplify things considerably.
|