6

i want to create a textbox in WPF that only accept numbers... i've reaserched and people say to use keypress event or masked textbox, but they are in windows forms...

Kourosh
  • 769
  • 2
  • 9
  • 20

1 Answers1

33

For WPF:

private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (!char.IsDigit(e.Text, e.Text.Length - 1))
        e.Handled = true;
}

For Windows Forms:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) )
        e.Handled = true;
}
Ulysses Alves
  • 2,297
  • 3
  • 24
  • 34
Maciek
  • 523
  • 1
  • 4
  • 8