仅限输入文本框" I-10"或" IV-12"或" III-7"

时间:2014-04-25 17:11:55

标签: c# textbox restrict

所以,我有一份功课,我需要帮助。我必须将文本框输入限制为类号。我们的课程格式为:" I-1"," II-1"," III-1"," IV-1", " I-10"," IV-10"等等。所以我的代码是:

private void tbRazred_KeyPress(object sender, KeyPressEventArgs e)
{ //ogranicenje textbox-a da moze da upisuje razred u formatu npr. IV-1
    duzina = tbRazred.TextLength;
    if (brprivremeni < duzina)
    {
        brprivremeni = duzina;
        if (e.KeyChar.ToString() != "-")
            switch (brslova)
            {
                case 1:
                    {
                        e.Handled = e.KeyChar != 'I'; brslova++;
                        break;
                    }
                case 2:
                    {
                        e.Handled = e.KeyChar != 'I' && e.KeyChar != 'V'; brslova++;
                        break;
                    }
                case 3:
                    {
                        if (tbRazred.Text == "IV") e.Handled = e.KeyChar != '-'; brslova++;
                        break;
                    }
                case 4:
                    {
                        if (tbRazred.Text == "III") e.Handled = e.KeyChar != '-'; brslova++;
                        break;
                    }
            }
        else e.Handled = !char.IsDigit(e.KeyChar);
    }
}

duzina获取文本框长度 btprivremeni是临时值,它获取文本框长度并与新文本框长度进行比较,因此如果它相同或更低,则它不会执行任何操作。请帮助我,我这样做了几天,现在我必须问你。

1 个答案:

答案 0 :(得分:0)

有几种不同的方法可以做到这一点。由于您的列表可能选项非常小,我会将所有&#34;类号和#34;到一个字符串列表。然后,我会使用来自其他控件的事件处理程序检查该列表中的文本框文本。

Textbox tbRazred = new Textbox();
List<string> classNumbers = new List<string>();
// Add all your items, here is one of them
classNumbers.Add("I-1");

// Call the following based on some checker routine or Control. Maybe when the Textbox loses focus?
bool pass = false;
foreach (string thisClass in classNumbers)
{
    if (thisClass == tbRazred.Text)
    {
        pass = true;
    }
}