pyCthon
pyCthon

Reputation: 12341

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 to 5, so no negative and no decimal as any value higher crashes the app. Thank you!

Upvotes: 0

Views: 845

Answers (2)

Nahydrin
Nahydrin

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

Sylver
Sylver

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

Related Questions