0

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!

3
  • 3
    atleyhunter.com/2010/11/12/… Commented 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 work Commented Jul 17, 2011 at 1:31
  • pity you didn't mention that in your question... Commented Jul 17, 2011 at 1:32

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

regexp for this is a bad idea
@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.
@ChrisWue: I am not sure how much resources it would use, but assuming it's too much, that makes sense.
@Selverdrag just an overkill all around. You almost never really need a regexp for anything, especially something as simple as checking a number range.
@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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.