In this article I will explain with an example, how to use Regular Expression (Regex) to accept/allow only Alphabets and Space in TextBox in Windows Forms (WinForms) Applications using C# and VB.Net.
When the Validate Button is clicked, the TextBox value will be validated using Regular Expression (Regex) in C# and VB.Net.
 
 
Form Design
The following Form consists of a TextBox, a Label and a Button.
Regular Expression (Regex) to accept only Alphabets and Space in TextBox in C# and VB.Net
 
 
Namespaces
You need to import the following namespace.
C#
using System.Text.RegularExpressions;
 
VB.Net
Imports System.Text.RegularExpressions
 
 
Validating Alphabets and Spaces using C# and VB.Net
When the Validate Button is clicked, the following event handler is executed.
Inside this event handler, 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)
{
    lblMessage.Hide();
    Regex regex = new Regex("[a-zA-Z ]$");
    if (!regex.IsMatch(txtAlphabets.Text.Trim()))
    {
        lblMessage.Show();
    }
}
 
VB.Net
Private Sub OnValidate(sender As Object, e As EventArgs) Handles btnValidate.Click
    lblMessage.Hide()
    Dim regex As Regex = New Regex("[a-zA-Z ]$")
    If Not regex.IsMatch(txtAlphabets.Text.Trim()) Then
        lblMessage.Show()
    End If
End Sub
 
 
Screenshots
Invalid Characters
Regular Expression (Regex) to accept only Alphabets and Space in TextBox in C# and VB.Net
 
Valid Characters
Regular Expression (Regex) to accept only Alphabets and Space in TextBox in C# and VB.Net
 
 
Demo
Regular Expression (Regex) to accept only Alphabets and Space in TextBox in C# and VB.Net
 
 
 
Downloads