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

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for How do I get a TextBox to only accept numeric input in WPF?

How to Make a TextBox Only Accept Numeric Input in WPF 😎💻

Are you tired of users freely entering non-numeric characters in your WPF TextBox? Do you want to restrict input to only numbers without having to deal with cumbersome arrow controls? Look no further! In this guide, we'll walk you through the easy and practical steps to achieve this.

Understanding the Problem

The challenge at hand is to allow users to input digits and decimal points while disallowing any other characters or signs.

Exploring the Options

You might have come across the NumericUpDown control for Windows Forms or the custom NumericUpDown control provided by Microsoft for WPF. But if you don't want to deal with the arrow controls, those options might not be the best fit for your needs.

The Simple Solution

Luckily, we have a simpler and more practical solution for you! By leveraging the power of regular expressions in WPF, you can easily validate and control the input of your TextBox. Here's how you can do it:

  1. Start by adding an event handler to the PreviewTextInput event of your TextBox. This event fires before the actual text is updated, giving us the chance to validate and filter the input.

<TextBox PreviewTextInput="TextBox_PreviewTextInput" />
  1. In the code-behind of your XAML file, implement the TextBox_PreviewTextInput event handler method.

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var textBox = (TextBox)sender;
    var proposedText = textBox.Text + e.Text;

    // Use a regular expression to validate the proposed text
    if (!Regex.IsMatch(proposedText, "^[0-9]*\\.?[0-9]*$"))
    {
        e.Handled = true; // Prevent the input from being applied
    }
}
  1. In the regular expression ^[0-9]*\\.?[0-9]*$, we specify the pattern for valid input. The expression allows for zero or more digits ([0-9]*), an optional decimal point (\\.?), and zero or more digits after the decimal point ([0-9]*).

That's it! You're Done! 🥳

By implementing this simple solution, you can now restrict your TextBox to accept only numeric input, including decimals. Users won't be able to enter any other characters or signs.

Engage with the Community

We hope this guide has helped you solve your problem efficiently. If you have any questions or need further assistance, don't hesitate to reach out to the vibrant WPF community. Share your thoughts and experiences in the comments section below, and let's learn from each other!

And remember, sharing is caring! If you found this guide useful, spread the word by sharing it with your fellow developers who might benefit from it. Happy coding! 👩‍💻👨‍💻

Thank you for reading!

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my