WPF TextBox Only Accepts Numbers


You have a TextBox in your WPF program that needs to only accept numbers. How do you do that? In this partial solution, we use the MaxLength property, the PreviewTextInput event, regular expressions and other techniques to restrict what the user may enter into the text box. Below is a screenshot of a user who has entered a number. We allow for decimal places here. The SelectionChanged event returns the number of characters the user has typed so far. If the user pastes (Copy/Paste) in some text, such as “ABC”, the text will go into the text box and the SelectionChanged event will fire and it will report the increase in characters to 8/15.

WPF TextBox Only Accepts Numbers

Below is the XAML. Notice that the TextBox has a Name. It has a PreviewTextInput event and limits the number of characters with MaxLength.

Keys from the Keyboard

This works well if you want to limit which keys from the keyboard are acceptable. It does not verify the end result of what the user has entered. To test that we’d need another button and an event that used another Regex to test the results. Also, users can paste text into the TextBox that contains alpha characters. Inside the XAML of the input text box, add the event PreviewTextInput. In the code-behind we need to add some code. Have a look at the listing and follow that pattern for your project.

<Window x:Class="TextBoxNumbersOnly.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TextBoxNumbersOnly"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="TextBoxNumbersOnly" Height="250" Width="420">
    <StackPanel Background="#A4C2F8C3">
        <TextBlock Margin="6,6,6,6" TextWrapping="Wrap">Limit what the user can type into a TextBox! In this example we will only allow numbers,
        the dash and the period to be entered. We will set the maximum number of characters entered to 15 with the 
            <Run FontWeight="Bold">MaxLength</Run> property. We use the <Run FontWeight="Bold">PreviewTextInput</Run> of the TextBox to trap the keystrokes
        that the user types. We also use Regular expressions to specify the allowed characters. Users can still type in as many dashes and periods as they
        like, up to the limit of 15 total characters. Also, the user can successfully Paste in character text. At least we have a good start
        with this solution. More work is needed.</TextBlock>
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBox Name="txtbxNumber" Margin="6,6,6,6" Width="140" Height="22" 
                 PreviewTextInput="txtbxNumber_PreviewTextInput" 
                 SelectionChanged="txtbxNumber_SelectionChanged"
                 MaxLength="15"></TextBox>
            <TextBlock Name="txtblkChars" VerticalAlignment="Center" Foreground="SlateGray">0/15</TextBlock>
        </StackPanel>
    </StackPanel>
</Window>

Below is the code behind in C#. Note that we need to add the statement using System.Text.RegularExpressions. Adjust the Regex to your own needs. Here we have Regex(“[0-9.-]+”). If you only wanted positive numbers, then do not allow the negative sign like this: Regex(“[0-9.]+”). Do you only want integers starting with 0? Try this: Regex(“[0-9]+”).

using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;

namespace TextBoxNumbersOnly
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void txtbxNumber_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = !IsTextAllowed(e.Text);
        }
        // allow all digits 0 to 9 plus the dot and the minus sign
        private static readonly Regex rgx = new Regex("[0-9.-]+"); 
        private static bool IsTextAllowed(string text)
        {
            return rgx.IsMatch(text);
        }
        private void txtbxNumber_SelectionChanged(object sender, RoutedEventArgs e)
        {   
            string str = txtbxNumber.Text;
            int len = txtbxNumber.Text.Length; 
            txtblkChars.Text = len + "/15";
        }
    }
}