c# - Array IndexOutOfRange -
string temp = textbox1.text; char[] array1 = temp.tochararray(); string temp2 = "" + array1[0]; string temp3 = "" + array1[1]; string temp4 = "" + array1[2]; textbox2.text = temp2; textbox3.text = temp3; textbox4.text = temp4; how prevent indexoutofrange error occurring when user inputs less 3 letters in textbox1?
how prevent indexoutofrange error if user input less 3 letters in textbox1?
just check using temp.length:
if (temp.length > 0) { ... } ... or use switch/case.
also, don't need array @ all. call tostring on each character, or use substring:
string temp = textbox1.text; switch (temp.length) { case 0: textbox2.text = ""; textbox3.text = ""; textbox4.text = ""; break; case 1: // via indexer... textbox2.text = temp[0].tostring(); textbox3.text = ""; textbox4.text = ""; break; case 2: // via substring textbox2.text = temp.substring(0, 1); textbox3.text = temp.substring(1, 1); textbox4.text = ""; break; default: textbox2.text = temp.substring(0, 1); textbox3.text = temp.substring(1, 1); textbox4.text = temp.substring(2, 1); break; } another option - neater - use conditional operator:
string temp = textbox1.text; textbox2.text = temp.length < 1 ? "" : temp.substring(0, 1); textbox3.text = temp.length < 2 ? "" : temp.substring(1, 1); textbox4.text = temp.length < 3 ? "" : temp.substring(2, 1);
Comments
Post a Comment