简体   繁体   中英

How can I use ASP.NET's Label IDs in a FOR loop in C#?

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.

ps: 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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM