Search code examples
c#winformstextbox

How to make a TextBox accept only alphabetic characters?


How can I make a TextBox only accept alphabetic characters with spaces?


Solution

  • You could use the following snippet:

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]"))
        {
            MessageBox.Show("This textbox accepts only alphabetical characters");
            textBox1.Text.Remove(textBox1.Text.Length - 1);
        }
    }