How to Get a Textbox to Only Accept Numeric Input in Wpf

How do I get a TextBox to only accept numeric input in WPF?

Add a preview text input event. Like so: <TextBox PreviewTextInput="PreviewTextInput" />.

Then inside that set the e.Handled if the text isn't allowed. e.Handled = !IsTextAllowed(e.Text);

I use a simple regex in IsTextAllowed method to see if I should allow what they've typed. In my case I only want to allow numbers, dots and dashes.

private static readonly Regex _regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
private static bool IsTextAllowed(string text)
{
return !_regex.IsMatch(text);
}

If you want to prevent pasting of incorrect data hook up the DataObject.Pasting event DataObject.Pasting="TextBoxPasting" as shown here (code excerpted):

// Use the DataObject.Pasting Handler 
private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!IsTextAllowed(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}

C# WPF How to use only numeric value in a textbox

You can add Previewtextinput event for textbox and validate the value inside that event using Regex,

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

Allow only numeric entry in WPF Text Box

The red border you've seen is actually a ValidationTemplate, which you can extend and add a info for the user. See this example:

    <UserControl.Resources>
<ControlTemplate x:Key="validationTemplate">
<Grid>
<Label Foreground="Red" HorizontalAlignment="Right" VerticalAlignment="Center">Please insert a integer</Label>
<Border BorderThickness="1" BorderBrush="Red">
<AdornedElementPlaceholder />
</Border>
</Grid>
</ControlTemplate>
</UserControl.Resources>

<TextBox Name="tbValue" Validation.ErrorTemplate="{StaticResource validationTemplate}">

TextBox with only numbers

You can either prevent any non-numeric input whatsoever, or just filter out digits in the text.

Preventing non-digit input

Use the BeforeTextChanging event:

<TextBox BeforeTextChanging="TextBox_OnBeforeTextChanging" />

And now handle like this:

private void TextBox_OnBeforeTextChanging(TextBox sender,
TextBoxBeforeTextChangingEventArgs args)
{
args.Cancel = args.NewText.Any(c => !char.IsDigit(c));
}

This LINQ expression will return true and hence Cancel the text change in case it encounters any non-digit character in the input.

Filtering non-digit input

Use the TextChanging event:

<TextBox TextChanging="TextBox_OnTextChanging" /> 

And handle this way:

private void TextBox_OnTextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
//Save the position of the selection, to prevent the cursor to jump to the start
int pos = sender.SelectionStart;
sender.Text = new String(sender.Text.Where(char.IsDigit).ToArray());
sender.SelectionStart = pos;
}

This LINQ query will filter out non-digit characters and create a new string only with the digits in the input.

It is preferable to use TextChanging and BeforeTextChanging, because TextChanged occurs too late, so the user would be confused by seeing characters temporarily display on the screen and immediately disappearing.

Create WPF TextBox that accepts only numbers

Most implementations I have seen so far are using the PreviewTextInput event to implement the correct mask behavior. This one inherits from TextBox and this one uses attached properties. Both use .Net's MaskedTextProvider to provide the correct mask behaviour, but if you just want a simple 'numbers only' textbox you don't need this class.

How do I get a TextBox to only accept numeric input in WPF?

Add a preview text input event. Like so: <TextBox PreviewTextInput="PreviewTextInput" />.

Then inside that set the e.Handled if the text isn't allowed. e.Handled = !IsTextAllowed(e.Text);

I use a simple regex in IsTextAllowed method to see if I should allow what they've typed. In my case I only want to allow numbers, dots and dashes.

private static readonly Regex _regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
private static bool IsTextAllowed(string text)
{
return !_regex.IsMatch(text);
}

If you want to prevent pasting of incorrect data hook up the DataObject.Pasting event DataObject.Pasting="TextBoxPasting" as shown here (code excerpted):

// Use the DataObject.Pasting Handler 
private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!IsTextAllowed(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}


Related Topics



Leave a reply



Submit