eomer
eomer

Reputation: 3624

Text box only digits

I know this question is asked but I have another problem in my code:

(e.Key >= Windows.System.VirtualKey.Number0) && 
(e.Key <= Windows.System.VirtualKey.Number9)

It works but when I type Shift+6 it types & the code wont work when shift press but after 6 is pressed it works and types as &.

How can I disable this? I am thinking a global variable that keeps the previous key and if it's shift don't type but it also keeps shift neither shift is pressed with a number key at the same time or shift is preesed before number key.

Upvotes: 0

Views: 556

Answers (4)

S3ddi9
S3ddi9

Reputation: 2151

You shoud use PreviewTextInput.it raises before any other textchanged or any other key event, if you set

  • e.Handled to True that means that all upcoming events have been handeled including (Textchanged,...), so they'll be canceled. if
  • e.Handeled false so everything continues Normaly

Next you try to parse the e.text (which is the new textbox value) to an int if its true (the text is an int) e.handeled=False so the textchanged,.. continue, otherwise e.Handeled=True sothing happens

NOTE on the preview event the textbox didn't changed yet, so you retrieve its value from e.Text

    TextBox mytextblock= new TextBox();
    mytextblock.PreviewTextInput += mytextblock_PreviewTextInput;

inside

    void mytextblock_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            int val;
            e.Handled = !int.TryParse(e.Text, out val);
        };

Upvotes: 0

Epsil0neR
Epsil0neR

Reputation: 1704

better use a Regex to check if user inputed a number, as user also can paste a value which also can be valid.

Use "^\d+$" if you need to match more than one digit.

Note that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩. Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9.

You should check keep in private member your valid value from textbox and every time text box value is changed, you must check if value is valid, if valid, then private member = textbox.value, else textbox.value = private member, in that case you user won't be able to input not valid value

Upvotes: 0

Robertas
Robertas

Reputation: 1222

You may as well check for special keys like Shift: Keyboard.Modifiers == ModifierKeys.Shift.

http://msdn.microsoft.com/en-us/library/system.windows.input.modifierkeys.aspx

Upvotes: 1

dutzu
dutzu

Reputation: 3920

Why don't you TryParse the incomming text and see if it's int rather then verifying the key.

If you wish to keep the current implementation then also check for Modifier keys to avoid cases like Shift+6.

Upvotes: 1

Related Questions