tags:

views:

296

answers:

4

Hi, this is my code:

<%
 for(int i = 0 ; i < 10 ; i++) {
%>
<asp:CheckBox ID="CheckBox<%=i %>" runat="server" />
<%
  }
%>

But this code is not working How can I add multiple controls using loops by this method?

A: 

You can't use server controls in this way. You can easily render the <input> HTML element yourself though.

<%
 for(int i = 0 ; i < 10 ; i++) {
%>
<input type="checkbox" id="CheckBox<%=i %>" name="Checkbox<%= i %>" />
<%
  }
%>

I'm not sure if this is what you want though, as you should handle the input manually using Request.Form.

Mehrdad Afshari
+2  A: 

Unfortunately, the <%= %> syntax cannot be used within tag bodies or attributes in ASP.NET. The <%= notation is a shorthand for Response.Write() - and so is limited in where it can be used.

What you can do instead, in your situation, is use the <asp:CheckBoxList> control. It provides better direct support for what you're trying to do, without the awkwardness.

LBushkin
Documentation for the CheckBoxList control: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkboxlist.aspx
Blixt
A: 

Here's an article that shows how to create dynamic controls:

Creating dynamic controls using ASP.NET 2.0 and C# .NET

Dana Holt