I have the following code to only allow letters in the text box:
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
Char pressedKey = e.KeyChar;
if (Char.IsLetter(pressedKey))
{
// Allow input.
e.Handled = false
}
else
e.Handled = true;
}
}
How can I allow the backspace key to work because, it doesnt let me to delete characters after typed
You can check if the key pressed is a Control character using Char.IsControl(...), like this:
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsLetter(e.KeyChar) && !Char.IsControl(e.KeyChar))
e.Handled = true;
}
If you specifically need to check only chars + Delete, use this:
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsLetter(e.KeyChar) && e.KeyChar != (char)Keys.Back)
e.Handled = true;
}
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