How to dynamically create a control in a for-loop on an ascx?

P

Peter

Hi

I have a slightly complicated web-application, where there is an ascx
which needs to create controls "dynamically".

The ascx has a large for-loop over a DataSet from which it extracts
various items of data to display in a list. There is also lots og logic
involved about what should be or should not be displayed.

Under some circumstances I need to display an extra control - that is I
need to dynamically create a control - but I get an error : "The
controls collection cannot be modified because the control contains
code blocks".

Here is a boiled down version which shows the problem. This is highly
simplified, and it is not a button I really want to generate (the
button here is just for example purposes). It is actually another user
control which is instantiated and delivered to me by some other code,
based on various parameters from the data in the DataSet.


<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="WebUserControl1.ascx.cs"
Inherits="WebApplication1.WebUserControl1" %>

<%@ Import Namespace="System.Collections.Generic" %>

<%
List<string> dataValues = Data; // get the data from code behind

for (int i = 0; i < dataValues.Count; i++)
{
string dataValue = dataValues;
%>
<!-- actually lots of complicated display logic here -->
<%=dataValue %>
<%
if (dataValue == "two")
{
Button b = new Button();
b.ID = "button_" + i;
b.Text = "my button";

this.Controls.Add(b);
}
%>
<br />
<%
}
%>


Note that I first used a Repeater, on which I had panels, which I could
"FindControl" in ItemDataBound, and add my dynamic controls to the
panels. This worked, but the repeater was very slow compared to a
for-loop.


Thank you,
Peter
 

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

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top