0

我需要将 textbox1 验证为 2 个字母和 2 个整数,即) ab11

我如何设置它我的文本框只接受 2 个字符和 2 个整数。

请帮我...

4

4 回答 4

0

这应该有效。

private void textBox1_TextChanged(object sender, EventArgs e)
{
    TextBox tb=sender as TextBox;
    string text=tb.Text;

    switch (text.Length)
    { 
        case 1:
            if (!char.IsLetter(text[0]))
                tb.Text = "";
            break;
        case 2:
            if (!char.IsLetter(text[1]))
                tb.Text = text.Remove(1);
            break;
        case 3: 
            if (!char.IsNumber(text[2]))
                tb.Text = text.Remove(2);
            break;
        case 4:
            if (!char.IsNumber(text[3]))
                tb.Text = text.Remove(3);
            break;
        default:
            if(text.Length>4)
                tb.Text = text.Substring(0, 4);
            break;
    }
    textBox1.Select(tb.Text.Length, 0);
}
于 2013-01-27T15:28:42.473 回答
0
string str = textBox1.Text;
if (Regex.IsMatch(str, @"^(([A-Z]|[a-z])([A-Z]|[a-z])\d\d)$"))
{
    MessageBox.Show("Valid");
}

参考:正则表达式类

于 2013-01-27T16:13:18.827 回答
0

如果:

string myString = textbox1.Text;

然后验证:

If (Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}$")))
{
   return true;
}
else
{
   return false;
}
于 2013-01-27T14:27:40.323 回答
0
   private void textBox2_Validating(object sender, CancelEventArgs e)
    {
        var cn = textBox2.Text.Where(c => char.IsLetter(c)).Count();
        var cd = textBox2.Text.Where(c => char.IsNumber(c)).Count();
        if (cn >= 2 && cd >= 2)
        {
            //Success, Do Stuff
        }
        else
        {
            e.Cancel = true;
        }
    }
于 2013-01-27T14:52:15.233 回答