[c#] How to make a TextBox accept only alphabetic characters?

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

This question is related to c# winforms textbox

The answer is


You can try by handling the KeyPress event for the textbox

void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}

Additionally say allow backspace in case you want to remove some text, this should work perfectly fine for you

EDIT

The above code won't work for paste in the field for which i believe you will have to use TextChanged event but then it would be a bit more complicated with you having to remove the incorrect char or highlight it and place the cursor for the user to make the correction Or maybe you could validate once the user has entered the complete text and tabs off the control.


private void textbox1_KeyDown_1(object sender, KeyEventArgs e)
{
    if (e.Key >= Key.A && e.Key <= Key.Z)
    {
    }
    else
    {
       e.Handled = true;
    }
}

you can try following code that alert at the time of key press event

private void tbOwnerName_KeyPress(object sender, KeyPressEventArgs e)
    {

        //===================to accept only charactrs & space/backspace=============================================

        if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
        {
            e.Handled = true;
            base.OnKeyPress(e);
            MessageBox.Show("enter characters only");
        }

Write Code in Text_KeyPress Event as

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (!char.IsLetter(e.KeyChar))
        {
            e.Handled = true;
        }
    }

private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar >= '0' && e.KeyChar <= '9')
                e.Handled = true;
            else
                e.Handled = false;
        }

works for me, even though not the simplest one.

private void Alpha_Click(object sender, EventArgs e)
        {
            int count = 0;
            foreach (char letter in inputTXT.Text)
            {
                if (Char.IsLetter(letter))
                {
                    count++;
                }
                else
                {
                    count = 0;
                }
            }
            if (count != inputTXT.Text.Length)
            {
                errorBox.Text = "The input text must contain only alphabetic characters";
            }
            else
            {
                errorBox.Text = "";
            }
        }

This solution uses regular expressions, does not allow invalid characters to be pasted into the text box and maintains the cursor position.

using System.Text.RegularExpressions;

int CursorWas;
string WhatItWas;

private void textBox1_Enter(object sender, EventArgs e)
    {
        WhatItWas = textBox1.Text;
    }

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]*$"))
        {
            WhatItWas = textBox1.Text;
        }
        else
        {
            CursorWas = textBox1.SelectionStart == 0 ? 0 : textBox1.SelectionStart - 1;
            textBox1.Text = WhatItWas;
            textBox1.SelectionStart = CursorWas;
        }
    }

Note: textBox1_TextChanged recursive call.


Here is my solution and it works as planned:

string errmsg = "ERROR : Wrong input";
ErrorLbl.Text = errmsg;

if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
{
  ErrorLbl.Text = "ERROR : Wrong input";
}
else ErrorLbl.Text = string.Empty;
if (ErrorLbl.Text == errmsg)
{
  Nametxt.Text = string.Empty;
}

This works fine as far as characters restriction, Any suggestions on error msg prompt with my code if it's not C OR L

Private Sub TXTBOX_TextChanged(sender As System.Object, e As System.EventArgs) Handles TXTBOX.TextChanged

        Dim allowed As String = "C,L"
        For Each C As Char In TXTBOX.Text
            If allowed.Contains(C) = False Then

                TXTBOX.Text = TXTBOX.Text.Remove(TXTBOX.SelectionStart - 1, 1)
                TXTBOX.Select(TXTBOX.Text.Count, 0)

            End If

        Next
      
    End Sub

The simplest way is to handle the TextChangedEvent and check what's been typed:

string oldText = string.Empty;
    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        if (textBox2.Text.All(chr => char.IsLetter(chr)))
        {
            oldText = textBox2.Text;
            textBox2.Text = oldText;

            textBox2.BackColor = System.Drawing.Color.White;
            textBox2.ForeColor = System.Drawing.Color.Black;
        }
        else
        {
            textBox2.Text = oldText;
            textBox2.BackColor = System.Drawing.Color.Red;
            textBox2.ForeColor = System.Drawing.Color.White;
        }
        textBox2.SelectionStart = textBox2.Text.Length;
    }

This is a regex-free version if you prefer. It will make the text box blink on bad input. Please note that it also seems to support paste operations as well.


        if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z]+$"))
        { 
        }
        else
        {
            textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
            MessageBox.Show("Enter only Alphabets");


        }

Please Try this


Try This

            private void tbCustomerName_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back||e.KeyChar==(char)Keys.Space);
    }

It Allows White Spaces Too


This one is working absolutely fine...

 private void manufacturerOrSupplierTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (char.IsControl(e.KeyChar) || char.IsLetter(e.KeyChar))
        {
            return;
        }
        e.Handled = true;
    }

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
      if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar) &&
         (e.KeyChar !='.'))
        { 
          e.Handled = true;
          MessageBox.Show("Only Alphabets");
        }
    }

Try following code in KeyPress event of textbox

if (char.IsLetter(e.KeyChar) == false  & 
        Convert.ToString(e.KeyChar) != Microsoft.VisualBasic.Constants.vbBack)
            e.Handled = true

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to textbox

Add two numbers and display result in textbox with Javascript How to check if a text field is empty or not in swift Setting cursor at the end of any text of a textbox Press enter in textbox to and execute button command javascript getting my textbox to display a variable How can I set focus on an element in an HTML form using JavaScript? jQuery textbox change event doesn't fire until textbox loses focus? PHP: get the value of TEXTBOX then pass it to a VARIABLE How to clear a textbox once a button is clicked in WPF? Get current cursor position in a textbox