In this article I will explain with an example, how to use Regular Expression (Regex) to accept/allow only Alphanumeric characters i.e. Alphabets (Upper and Lower case) and Numbers (Digits) in Windows Forms (WinForms) Application using C# and VB.Net.
 
 

Form Design

The following Form consists of:
TextBox – For capturing Alphanumeric characters.
Label – For showing error message.
Button – For validating Alphanumeric characters.
Regular Expression (Regex) to accept only Alphanumeric (Alphabets and Numbers) in C# and VB.Net
 
The Button has been assigned with the Click event handler.
Regular Expression (Regex) to accept only Alphanumeric (Alphabets and Numbers) in 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 Expression (Regex) to accept only Alphanumeric (Alphabets and Numbers)

Regular Expression (Regex)

^[a-zA-Z0-9]*$
 

Explanation

Above Regular Expression accept only Alphanumeric.
Alphabets (Upper and Lower case) and Numbers (Digits) as valid characters.
 

Example

When the Validate Button is clicked, the value of the TextBox is validated against the Regular Expression (Regex) and if invalid, the error message is displayed.
C#
private void OnValidate(object sender, EventArgs e)
{
    lblError.Hide();
    Regex regex = new Regex(@"^[a-zA-Z0-9]*$");
    if (!string.IsNullOrEmpty(txtAlphaNumeric.Text.Trim()))
    {
        if (!regex.IsMatch(txtAlphaNumeric.Text.Trim()))
        {
            lblError.Show();
        }
    }
    else
    {
        lblError.Text "Alphanumeric characters are required";
        lblError.Show();
    }
}
 
VB.Net
Private Sub OnValidate(sender As Object, e As EventArgs) Handles btnValidate.Click
    lblError.Hide()
    Dim regex As Regex = New Regex("^[a-zA-Z0-9]*$")
    If Not String.IsNullOrEmpty(txtAlphaNumeric.Text.Trim())Then
        If Not regex.IsMatch(txtAlphaNumeric.Text.Trim())Then
            lblError.Show()
        End If
    Else
        lblError.Text "Alphanumeric characters are required"
        lblError.Show()
    End If
End Sub
 
 

Screenshots

Invalid values

Regular Expression (Regex) to accept only Alphanumeric (Alphabets and Numbers) in C# and VB.Net
 
Regular Expression (Regex) to accept only Alphanumeric (Alphabets and Numbers) in C# and VB.Net
 

Valid Value

Regular Expression (Regex) to accept only Alphanumeric (Alphabets and Numbers) in C# and VB.Net
 
 

Demo

Regular Expression (Regex) to accept only Alphanumeric (Alphabets and Numbers) in C# and VB.Net
 
 

Downloads