In this article I will explain with an example, how to allow both decimals as well as integers and any decimal number in Windows Forms (WinForms) Application using C# and VB.Net.
When the Submit Button is clicked, the TextBox will be validated using Regular Expression (Regex) using C# and VB.Net.
In this article following validation will be performed.
1. Allow both decimals as wells as integers numbers.
2. Allow any decimal number starting from 1 up to N decimal places.
 
 
Form Design
The following Form consists of some Labels, two TextBoxes and two Button controls.
Regular Expression (Regex) to allow decimals and integers using C# and VB.Net
 
 
Namespaces
You will need to import the following namespace.
C#
using System.Text.RegularExpressions;
 
VB.Net
Imports System.Text.RegularExpressions
 
 
Regular Expressions (Regex) to allowing both decimals as wells as integers
Regular Expression (Regex)
^((\d+)((\.\d{1,2})?))$
 
Explanation
This Regular Expression validates for any number of digits. And if dot character is added it validates up to 2 decimals.
 
Example
When the Validate Button is clicked, the value of the TextBox is validated against the Regular Expression (Regex) and if invalid, the error Label is displayed.
C#
private void OnValidate1(object sender, EventArgs e)
{
    lblMessage1.Hide();
    Regex regex1 = new Regex(@"^(\d+)((\.\d{1,2})?)$");
    if (!regex1.IsMatch(txt1.Text.Trim()))
    {
        lblMessage1.Show();
    }
}
 
VB.Net
Private Sub OnValidate1(sender As Object, e As EventArgs) Handles btnValidate1.Click
    lblMessage1.Hide()
    Dim regex1 As Regex = New Regex("^((\d+)((\.\d{1,2})?))$")
    If Not regex1.IsMatch(txt1.Text.Trim()) Then
        lblMessage1.Show()
    End If
End Sub
 
 
Regular Expressions (Regex) to allowing any decimal number starting from 1 up to N decimal places
Regular Expression (Regex)
^((\d+)+(\.\d+))$
 
Explanation
This Regular Expression validates any number of digits followed by a dot character and ending with minimum one decimal place.
 
Example
When the Submit Button is clicked, the value of the TextBox is validated against the Regular Expression (Regex) and if invalid, the error Label is displayed.
C#
private void OnValidate2(object sender, EventArgs e)
{
    lblMessage2.Hide();
    Regex regex2 = new Regex(@"^((\d+)+(\.\d+))$");
    if (!regex2.IsMatch(txt2.Text.Trim()))
    {
        lblMessage2.Show();
    }
}
 
VB.Net
Private Sub OnValidate2(sender As Object, e As EventArgs) Handles btnValidate2.Click
    lblMessage2.Hide()
    Dim regex2 As Regex = New Regex("^((\d+)+(\.\d+))$")
    If Not regex2.IsMatch(txt2.Text.Trim()) Then
        lblMessage2.Show()
    End If
End Sub
 
 
Screenshots
Invalid values
Regular Expression (Regex) to allow decimals and integers using C# and VB.Net
 
Valid values
Regular Expression (Regex) to allow decimals and integers using C# and VB.Net
 
 
Demo
Regular Expression (Regex) to allow decimals and integers using C# and VB.Net
 
 
Downloads