3

i want to make a textbox in my wpf application which will accept only integer values. if someone types characters between [a-z], the textbox will reject it. Thus it will not be displayed in the textbox

2

5 Answers 5

7

You can handle the PreviewTextInput event:

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
  // Filter out non-digit text input
  foreach (char c in e.Text) 
    if (!Char.IsDigit(c)) 
    {
      e.Handled = true;
      break;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

In WPF, you can handle the KeyDown event like this:

private void MyTextBox_KeyDown(object sender, KeyDownEventArgs e)
{
    e.Handled = true;
}

2 Comments

This will only prevent from entering text, but not from paste from clipboard.
copy/paste will always require a special tratment with post validation anyway, but the idea of doing a prefilter is probably better in this case. It can then be coupled with a post-validation. I would rather use the PreviewTextInput event instead of the KeyDOwn event though
1

You can add handle of the TextChanged event and look what was entered (need to check all text every time for preventing pasting letters from clipboard).

Also look a very good example of creating maskable editbox on CodeProject.

Comments

1

this simple code snippet should do the trick.. You might also want to check for overflows (too large numbers)

private void IntegerTextBox_TextChanged(object sender, EventArgs e)
{
    for (int i = 0; i < Text.Length; i++)
    {
        int c = Text[i];
        if (c < '0' || c > '9')
        {
           Text = Text.Remove(i, 1);
         }
    }
}

2 Comments

this does not prevent the user to type a "non-integer", it just removes it when it has been typed. Jogy's solution using the previewTextInput methods seems better. Your solution could be used as a post validation though (case of copy/paste)
Yes you are right, sometimes you can see "flickering" where the text appears and then disappears when this code is used. I guess the best solution is a combination of both.
1

Bind it to Integer property. WPF will do the validation itself without any extra hassle.

Comments

Your Answer

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