In this article I will explain with an example, how to perform Numeric validation using
Regular Expression in Windows Forms (WinForms) Application using C# and VB.Net.
Form Design
The following Form consists of one TextBox, one Label and a Button control.
Namespaces
You will need to import the following namespace.
C#
using System.Text.RegularExpressions;
VB.Net
Imports System.Text.RegularExpressions
Regular Expression (Regex) to validate Numeric value
Regular Expression (Regex)
^[0-9]+$
Explanation
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 OnValidate(object sender, EventArgs e)
{
lblError.Hide();
Regex regex = new Regex("^[0-9]+$");
if (!regex.IsMatch(txtNumber.Text.Trim()))
{
lblError.Show();
}
}
VB.Net
Private Sub OnValidate(sender As Object, e As EventArgs) Handles btnValidate.Click
lblError.Hide()
Dim regex As Regex = New Regex("^[0-9]+$")
If Not regex.IsMatch(txtNumber.Text.Trim()) Then
lblError.Show()
End If
End Sub
Screenshots
Invalid Value
Valid Value
Demo
Downloads