Tony
Tony

Reputation: 12695

ASP.NET Dynamically creating & setting different ID for the same controls

is it possible to render the same controls with different ID property ?

<%for (int i = 0; i < 15; i++)
  {%>
     <asp:Label ID='Label<%=i.ToString() %>' runat="server"/>
<%}%>

here is an error: 'Label<%=i.ToString() %>' is not a valid identifier.

Upvotes: 1

Views: 4275

Answers (2)

Jaider
Jaider

Reputation: 14884

Usually in cases like this, you don't need to create asp.net controls... so, you can do this:

<%for (int i = 0; i < 15; i++)
  {%>
     <label id="Label<%=i.ToString() %>"></label>
<%}%>

Upvotes: 1

Alex Reitbort
Alex Reitbort

Reputation: 13696

Yes, it is possible but from code behined, not WebForms mark-up. From WebForm mark-up you can add only "html" controls in loop, not "asp.net" controls.

From code behind you can do:

for( int i=0;i<15;i++)
{
    var l = new Label();
    Label.ID = "Label" + i;
    Controls.Add(l);
}

Upvotes: 2

Related Questions