【问题标题】:TextBox Keypress Event Validation文本框按键事件验证
【发布时间】:2014-02-11 17:07:26
【问题描述】:

我想根据用户输入(按键事件)对我的文本框进行验证。我已将文本框的最大长度设置为 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;
            }
    }

有什么建议吗?

【问题讨论】:

  • 您介意详细说明“不起作用”吗?这并不能告诉我们太多。编译错误?运行时异常?意外行为?如果行为出乎意料,最好的解决方法是单步调试代码。我们不能那样做。
  • 另外,听起来您想尝试一些正则表达式来验证文本框的内容。可能比尝试验证每一次按键更容易。
  • 哦,对不起,我的意思是它有一些意想不到的行为。当我在文本框中输入第一个字符时,如果它是字符而不是数字,它会接受。但是当我在文本框中输入第二个字符时,它不接受它是字符还是数字。我试过单步执行代码,但仍然感到困惑。对不起我的英语不好。
  • 没问题,其实你的英文还不错。

标签: c# event-handling keypress


【解决方案1】:

这应该可以工作

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

【讨论】:

    【解决方案2】:
        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;
       }
    

    【讨论】:

    • 第一个字符文本框为空。所以首先如果你可以检查它。对于 2 下一个字符,您的文本框长度为 1 或 2。否则输入字符不正确
    • @user3233787 关于你的问题我已经告诉过你,看来我需要再告诉你一次。您对问题的详细说明不足以让 Mostafa 有机会修复代码以使其正常工作。如果您拒绝详细说明“它不起作用”之外的其他细节,那么您将得到的就是这么多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多