How to make a TextBox accept only alphabetic characters?

How can I make a TextBox only accept alphabetic characters?

Answers


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);
    }
}

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.


Need Your Help

Draw UIImage From CIImage In drawRect:

objective-c ios cocoa-touch core-image

I'm learning about drawing UIImages and CGImages, using CIFilters etc. To test my knowledge I made a small test app with sliders that programmatically change the color of a potion sprite and displa...

Build a 3d surface plot using xyz coordinates with jzy3d

java graph coordinates 3d

I've been searching for a way to send a list of coord(x,y,z) to jzy3d. But without success.

how to make elements Aligned inside div

css

I have a div with few elements , my label and textbox inside a div are not well aligned , You can see the screenshot ..

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.