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

reggie
  • 13,313
  • 13
  • 41
  • 57
  • 3
    I think this type of question has been asked before. See http://stackoverflow.com/questions/1346707/validation-in-textbox-in-wpf – Nipuna Mar 08 '11 at 12:58
  • Why dont yoy use DataValidation in WPF which is built exactly for this kind of things? http://www.wpftutorial.net/DataValidation.html – NVM Mar 08 '11 at 13:45

5 Answers5

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;
    }
}
Jogy
  • 2,465
  • 1
  • 14
  • 9
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.

kyrylomyr
  • 12,192
  • 8
  • 52
  • 79
1

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

private void MyTextBox_KeyDown(object sender, KeyDownEventArgs e)
{
    e.Handled = true;
}
John Gietzen
  • 48,783
  • 32
  • 145
  • 190
  • 3
    This will only prevent from entering text, but not from paste from clipboard. – kyrylomyr Mar 08 '11 at 12:58
  • 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 – David Mar 08 '11 at 15:16
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);
         }
    }
}
Can Gencer
  • 8,822
  • 5
  • 33
  • 52
  • 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) – David Mar 08 '11 at 15:14
  • 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. – Can Gencer Mar 08 '11 at 15:21
1

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

Matěj Zábský
  • 16,909
  • 15
  • 69
  • 114