vb.net - Validating String User Entry -


my issue attempting make user able enter "a, b, c or d". rather have error out if did not enter 1 of 4 letters user being able input letters. have been able find resources similar numeric data (using try catch). sites or hints great.

                if string.compare(textbox2.text, "a", true) = 0 andalso string.compare(textbox21.text, "a", true) = 0                 'messagebox.show("a")                 totcorrect = totcorrect + corans             elseif string.compare(textbox2.text, "b", true) = 0 andalso string.compare(textbox21.text, "b", true) = 0                 'messagebox.show("b")                 totcorrect = totcorrect + corans             elseif string.compare(textbox2.text, "c", true) = 0 andalso string.compare(textbox21.text, "c", true) = 0                 'messagebox.show("c")                 totcorrect = totcorrect + corans             elseif string.compare(textbox2.text, "d", true) = 0 andalso string.compare(textbox21.text, "d", true) = 0                 'messagebox.show("d")                 totcorrect = totcorrect + corans             else                 totwrong = totwrong + wrgans                 label13.visible = true             end if 

this should trick

private sub textbox1_keypress(sender object, e keypresseventargs) handles textbox1.keypress      dim allowablechar new list(of char) {"a"c, "b"c, "c"c, "d"c}      call allowablechar.addrange(allowablechar.select(function(c) convert.tochar(c.tostring().toupper())).tolist())      if not (allowablechar.contains(e.keychar) orelse e.keychar = convert.tochar(keys.delete) orelse e.keychar = convert.tochar(keys.back))         e.handled = true     end if  end sub 

the call allowablechar.addrange(...) adds upper case characters list well. now, generates new list every time method executes, bit wasteful... if use piece of code suggest list of allowable chars class-level variable , fill once in constructor of form.

to allow once character of each type, use this:

private sub textbox1_keypress(sender object, e keypresseventargs) handles textbox1.keypress      dim allowablechar new list(of char) {"a"c, "b"c, "c"c, "d"c}      call allowablechar.addrange(allowablechar.select(function(c) convert.tochar(c.tostring().toupper())).tolist())      if not (allowablechar.contains(e.keychar) orelse e.keychar = convert.tochar(keys.delete) orelse e.keychar = convert.tochar(keys.back))         e.handled = true     else         if me.textbox1.text.count(function(c) c = e.keychar) >= 1             e.handled = true         end if     end if  end sub 

Comments