How can I make a TextBox
only accept alphabetic characters with spaces?
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With