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

Discussion in 'ASP .Net Web Controls' started by Peter, Mar 23, 2009.

  1. Peter

    Peter Guest

    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
     
    Peter, Mar 23, 2009
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Quentin
    Replies:
    1
    Views:
    489
    Quentin
    Jul 29, 2003
  2. Jason Shohet
    Replies:
    1
    Views:
    484
    Kevin Spencer
    Nov 10, 2003
  3. Holger (David) Wagner
    Replies:
    2
    Views:
    1,943
    Holger (David) Wagner
    Jul 3, 2004
  4. Joe
    Replies:
    1
    Views:
    374
    Jeffrey Tan[MSFT]
    Feb 16, 2004
  5. Isaac Won
    Replies:
    9
    Views:
    382
    Ulrich Eckhardt
    Mar 4, 2013
Loading...

Share This Page