Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow backspace button to work in validated TextBox

Tags:

c#

.net

winforms

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

like image 603
user2154328 Avatar asked Oct 27 '25 03:10

user2154328


1 Answers

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;
}
like image 165
Jakob Möllås Avatar answered Oct 29 '25 17:10

Jakob Möllås



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!