how to dynamically create ocntrols?

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.

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 juet 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;
%>
<%=dataValue %>
<%
if (dataValue == "two")
{
Button b = new Button();
b.ID = "button_" + i;
b.Text = "my button";

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


Thanks,
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

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top