文本框按键事件验证



我想根据用户输入(按键事件)对我的文本框进行验证。我已将文本框的最大长度设置为 3 个字符。用户输入的第一个字符应为字符(从 a-z),然后两个后续字符必须是数字。允许退格。到目前为止,我有这段代码,但不能按我想要的方式工作。

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            countChar = this.textBox1.Text;
            if (String.IsNullOrEmpty(this.textBox1.Text))
            {
                e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
            }
            else if (countChar.Length == 1)
            {
                e.Handled = e.KeyChar == (char)Keys.Back;
            }
            else if (countChar.Length == 2 || countChar.Length == 3)
            {
                e.Handled = e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == (char)8;
            }
    }

有什么建议吗?

这应该有效

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        countChar = this.textBox1.Text;
        if (String.IsNullOrEmpty(this.textBox1.Text))
        {
            e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
        }
        else if (countChar.Length == 1 || countChar.Length == 2)
        {
            e.Handled = !(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back);
        }
        else if (countChar.Length == 3)
        {
            e.Handled = e.KeyChar != (char)Keys.Back;
        }
        else
        {
            e.Handled = true;
        }
    }
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        countChar = this.textBox1.Text;
        if (String.IsNullOrEmpty(this.textBox1.Text))
        {
            e.Handled = (char.IsLetter(e.KeyChar);
        }
        else if (countChar.Length == 1 || countChar.Length == 2)
        {
            e.Handled = e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == (char)8;
        }
       e.Handled=false;
   }

相关内容

  • 没有找到相关文章

最新更新