Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How Do I Make a textbox Class Which Only Takes Numeric Data in WPF Application

0.00/5 (No votes)
3 Aug 2016 1  
Making a TextBoxClass allows only numeric data

Introduction

Firstly, we try to create new WPF application. And add a new class. In my example class, the name is Class1.

Background

Image 1

C#
textBox.PreviewTextInput += 
new System.Windows.Input.TextCompositionEventHandler(Class1.PreviewTextInput);

Each textBox using Class1, it will have numerical property.

Using the Code

In MainWindow (WPF page), I added my code in constructor. But you can add where you need this.

WPF Page

C#
public MainWindow()
        {
            InitializeComponent();
            textBox.Text = "";
            textBox.PreviewTextInput += 
            new System.Windows.Input.TextCompositionEventHandler(Class1.PreviewTextInput);
        }

Class

C#
public static void PreviewTextInput(object sender, TextCompositionEventArgs e)
       {
           bool approvedDecimalPoint = false;

           if (e.Text == ".")
           {
               if (!((TextBox)sender).Text.Contains("."))
                   approvedDecimalPoint = true;
           }

           if (!(char.IsDigit(e.Text, e.Text.Length - 1) || approvedDecimalPoint))
               e.Handled = true;
       }

Points of Interest

Add libraries.

C#
using System.Windows.Controls;
using System.Windows.Input;

History

  • 3rd August, 2016: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here