In this post, we want to discuss a nice function to user provide numeric input only in WPF. Before we get started, if you want to know how to customize web form size, please go through the following article: Display custom size web form using JavaScript.
What is a Numeric only textbox?
This example shows the way to stop a user from providing alphabetical or symbolic inputs during a WPF input field. This instance is sort of easy however may be terribly helpful to stop any run time error.
Why Numeric only textbox needed
Suppose, you’ve got developed an associate degree application that keeps track of the daily financial gain and expense of a store. To do that, you’ve got to feature and figure values in numerous places. however, a user may give associate degree alphabetical input within the textbox, and eventually, the appliance would crush. To stop that, you’ll merely write a code to prevent users from providing anything instead of numeric input.
Methods for Numeric Only Input
First, write a new function that takes one string input and two lines of code inside it.
1 2 3 4 5 6 7 | public static bool onlyNumeric(string text) { Regex regex = new Regex(“[^0-9.-]+”); //regex that allows numeric input only return !regex.IsMatch(text); // } |
Then add a textbox in a WPF application and Create a new event:
1 2 3 | PreviewTextInput=”textBox1_PreviewTextInput” |
A new function for that event would be created on the cs page automatically. Now write the following line inside the newly created function:
1 2 3 | e.Handled = !onlyNumeric(e.Text); |
Also, add the below line at the top of the cs page:
1 2 3 | using System.Text.RegularExpressions; |
All done. Now run the application and you will see that the WPF textbox would take numeric input only.
User Provide Numeric Input Only in WPF
The article was published on July 2, 2016 @ 3:36 PM
Leave a Comment