user2154328
user2154328

Reputation: 53

Allow backspace button to work in validated TextBox

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

Upvotes: 4

Views: 15392

Answers (2)

Bill Kindig
Bill Kindig

Reputation: 3622

This is for those using VB.net. There's a weird conversion I'd never come across that took me a while to figure out.

This allows only numbers, letters, backspace and space.

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    e.Handled = e.KeyChar <> ChrW(Keys.Back) And Not Char.IsLetter(e.KeyChar) And Not Char.IsDigit(e.KeyChar) And Not Char.IsSeparator(e.KeyChar)
End Sub

Upvotes: 0

Jakob M&#246;ll&#229;s
Jakob M&#246;ll&#229;s

Reputation: 4369

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

Upvotes: 3

Related Questions