Using a for loop in server side code to cycle through labels by dynamically creating the names there
asp.net, c#
Solution
- Put all of the labels into some container, such as a `Panel` or `PlaceHolder`. Give that container an ID.
- In your code get the container by ID.
- Iterate the `Controls` collection of that container to get each of the labels. Use `OfType<Label>` if it's possible for there to be other types of controls besides labels.
Problem
I was working on a website that had a list of asp labels. I used javscript code to get the name of each box so I could modify the text that was inside them. I was using a for loop similiar to this, and I became curious if there was a way to call all the labels similiarly so that you can put them in a loop and to cycle through them all. Something like this in the server side code: asp code: ``` <asp:Label runat="server" ID="lblWorld1" Text="" /> <asp:Label runat="server" ID="lblWorld2" Text="" /> <asp:Label runat="server" ID="lblWorld3" Text="" /> <asp:Label runat="server" ID="lblWorld4" Text="" /> <asp:Label runat="server" ID="lblWorld5" Text="" /> ``` c# code ``` for(int c = 1; c <= 5 ; c++) { var label = "lblWorld" + c.toString(); label.Text = "Hello World!"; } ``` However, in the server side code, this doesn't work. Is there a way to make a for loop and with a dynamic system getting the name of the labels.