So, I have a homework and I need help. I must restrict my textbox input to class number. Our classes are in format: "I-1", "II-1", "III-1", "IV-1", "I-10", "IV-10" and so on. So my code is:
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 gets the textbox length btprivremeni is temporary value which gets the textbox length and its compared to the new textbox length, so if its same or lower it doesn't do anything. Please help me, I'm doing this for a couple days and now I must ask you.
There's a few different ways to do this. Since your list potential options is pretty small, I would put all of the "Class Numbers" into a list of strings. I would then check the textbox's text against that list with an Event Handler from some other control.
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;
}
}