[Solved] Use a variable in a for loop for a panel or textbox [closed]


Assuming you’ve got some number of textboxes named textbox1, textbox2, etc., you can’t just put a variable in the name and have it refer to the right textbox. You should put the textboxes in an array first.

TextBox[] textboxArray = new TextBox[] { textbox1, textbox2, textbox3, ... };
string alpha = "acdefde";
for (int i = 0; i < alpha.Length; i++)
{
    textboxArray[i].Text = alpha[i].ToString();
}

EDIT

Note that this does no error checking whatsoever, so if you give it a string that’s too long it’ll blow up. That’s not that big an issue here where the length of both items are known at compile time, but nevertheless here’s a fix: change i < array.Length to i < array.Length && i < textboxArray.Length. If you were to put this into a more general function, I’d have it throw an exception if the number of textboxes given isn’t exactly equal to the length of the string given.

solved Use a variable in a for loop for a panel or textbox [closed]