2
votes

Sorry if the title is not clear enough. I have about 20 Label and 20 TextBoxes in my asp.Net form and the Visible attribute for all of them is false.

I'm willing to change some of their Visible attributes to true, depending on a given number. How can I use those Labels and TextBoxes' IDs in a FOR loop?

I've named the Labels like this: Label1, Label2, Label3, etc.

p.s: The ParameterCount's value varies from 1 to 20.

for (int i = 0; i <= parameterCount; i++)
{
    Label[i].Visible = True; //I know it's wrong, but something like this
}

Example 1: ParameterCount = 4

(Label1, Label2, Label3, Label4).Visible = True

Example2: Parameter Count=2

(Label1, Label2).Visible = True

3
How do you give IDs to your labels?choz
Label1, Label2, Label3, etc.iminiki

3 Answers

3
votes

Simply put your label in an array:

Label[] arr = new Label[] { label1, label5, label10, lable13, label14 };
for (int i = 0; i < ParameterCount; ++i)
   arr[i].Visible = true;

Provided that ParameterCount <= arr.Length

2
votes

Use Page.FindControl:

Label l = this.FindControl($"Label{i}") as Label;

if (l != null)
{
    // use the label `l` here
}

If the label isn't a top element, you have to find it inside the container control.

See a full example on MSDN: How to: Access Server Controls by ID

0
votes

You could place those labels or textboxes inside an asp:Panel:

<asp:Panel ID="myPanel" runat="server">
    ... your textboxes and labels come here
</asp:Panel>

and then simply toggle the visibility of this panel:

myPanel.Visible = true; // or false if you wish