How to make a textbox receive only numbers

Asked

Viewed 1,031 times

3

How do I make for a textbox receive only number, but only for WPF. With winform I can do, but with WPF I could not yet.

1 answer

1


You can use the event PreviewTextInput of TextBox.

1. Layout (XAML)

Add the Previewtextinput event to your Textbox:

<TextBox HorizontalAlignment="Left" Height="23" Margin="10,181,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" PreviewTextInput="TextBox_PreviewTextInput"/>

2. Code Behind (.Cs)

Add the following using:

using System.Text.RegularExpressions;

Add the method for the Previewtextinput event:

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var textBox = sender as TextBox;
    e.Handled = Regex.IsMatch(e.Text, "[^0-9]+");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.