我想根据用户输入(按键事件)对我的文本框进行验证。我已将文本框的最大长度设置为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;
}
}
有什么建议吗?
答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
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;
}