4

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.

0

2 Answers 2

5
  1. Put all of the labels into some container, such as a Panel or PlaceHolder. Give that container an ID.
  2. In your code get the container by ID.
  3. 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.
Sign up to request clarification or add additional context in comments.

Comments

0

You can follow through with your current logic with:

for(int c = 1; c <= 5 ; c++)
{
var label = "lblWorld" + c.toString();
Label tempLabel = new Label;
tempLabel.ID = label.ToString();
tempLabel.Text = "Hello World!";   
}

You'll still need to deal with assigning values to individual labels though, so it's probably more scalable to handle the labels as a container.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.