How to make a text field that is allowed only an integer value?

I want to make a text box in my wpf application that will only accept integer values. if someone types between [az], the text box will reject it. Thus, it will not appear in the text box

+3
source share
5 answers

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;
    }
}
+7
source

You can add an event descriptor TextChangedand see what was entered (it is necessary to check all the text each time to prevent pasting letters from the clipboard).

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

+1

WPF KeyDown :

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

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

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);
         }
    }
}
+1
source

Bind it to the Integer property. WPF will independently validate without any additional problems.

+1
source

All Articles