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...

0

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

be careful with copy pasting into your box, won't be controlled by such a code
Easy solve Maciek and J3soon appreciated

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.