Create Control Dynamcially

º

ºa¤Ö

In tradition ASP, i can create a template like follow

<%
for i = 1 to 3
%>
<table>
<tr>
<td>Name: </td>
<td><input type="text" name="textName<%=i%>"/></td>
</tr>
</table>
<%
next
%>

But how to do it in ASP.net? I have tried using like this

<%
for (int i = 1; i < 3; i++) {%>
<table>
<tr>
<td>Name: </td>
<td><asp:TextBox id="textName<%#i%>"/></td>
</tr>
</table>
<%
} %>

but it not works....thanks
 
J

Juan T. Llibre

You were very close. This works, sort of :

<table>
<% for (int i = 1; i < 3; i++) { %>
<tr>
<td>Name: </td>
<td><asp:TextBox id="textName<%=i%>"/></td>
</tr>
<% } %>
</table>

If you view source, you'll see "textname1" and "textname2",
but that isn't very useful, is it ?

I say "sort of" because you can use this to repeat blocks of text,
with different font sizes, like the example in the QuickStart:
http://beta.asp.net/QUICKSTART/aspnet/samples/pages/intro/intro2_cs.aspx
but you cannot create controls with this type of code, because
as soon as you insert a second set of quotes into the line, i.e.,

<td><asp:TextBox id="textName<%=i%>" runat="server"/></td>

....the compiler will throw an exception.

So, you can use that type of code, to repeat any text,
IF you use only one set of quotes inside your brackets.

While <% %> code blocks provide a powerful way to custom manipulate
the text output returned from an ASP.NET page, they do not provide a
clean HTML programming model.

See :
http://beta.asp.net/QUICKSTART/util/srcview.aspx?path=~/aspnet/samples/pages/intro/intro3.src

As the sample above illustrates, developers using only <% %> code blocks
must custom manage page state between round trips and custom interpret posted values.

<%
This recommendation is from :
http://beta.asp.net/QUICKSTART/aspnet/doc/pages/pages.aspx#writingpages
%>

See intro2.aspx and intro3.aspx
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top