允许退格按钮在验证文本框中工作

本文关键字:工作 文本 验证 许退格 按钮 | 更新日期: 2023-09-27 18:03:26

我有以下代码只允许在文本框中出现字母:

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

我怎么能让退格键工作,因为,它不允许我删除字符后输入

允许退格按钮在验证文本框中工作

您可以使用Char.IsControl(...)检查按下的键是否为Control字符,如下所示:

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsLetter(e.KeyChar) && !Char.IsControl(e.KeyChar))
        e.Handled = true;
}

如果你特别需要只检查字符+ Delete,使用这个:

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsLetter(e.KeyChar) && e.KeyChar != (char)Keys.Back)
        e.Handled = true;
}

这是为那些使用VB.net的人准备的。有一个奇怪的转变,我从来没有遇到过,我花了很长时间才弄清楚。

允许只允许数字、字母、退格和空格。

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