1

How do I programmatically create an array of web user controls?

I created a web user control. I already know how to implement one of them coding in the aspx file, however I would like to know if it is possible to do that from the code behind in either the Page_Init() or the Page_Load() event.

I already know the initialization on the aspx page.

<%@ Register TagPrefix="uc" TagName="myUsercontrol1" Src="/Controls/myUsercontrol1.ascx" %>

In the traditional way, I would do something like:

<div id="divMyusercontrols" runat="server">
    <uc:myUsercontrol1 id="ctlTheControl" runat="server" />
</div>

What I was wanting to do, which does not work, as I tried, is:

In the aspx file:

<div id="divMyusercontrols" runat="server">
</div>

In the code behind in let us say the Page_Init() event the following:

String strControl = "<uc:myUsercontrol1 id="ctlTheControl{0}" runat="server" />";
String strHtml = null;
for (int i = 0; i < 5; i++)
     strHtml += String.Format(strControl, i.ToString());
this.divMyusercontrols.InnerHTML = strHtml;

This code sadly does not work. I realize that I can simply do that manually, but I do not know the actual count. I will know that ahead of time.

UPDATE (to show answer #3 proper code):

The C# for the aspx file is the following. I have a call to a static C# code behind, which returns the count. I then set a property to indicate which item to show and then the for-loop. Cool!

<%int iCount = MyProject.Items;%>
<%for (int iIndex = 0; iIndex < iCount; iIndex++)%>
<%{ %>
    <div runat="server">
    <uc:myUsercontrol1 id="ctlItem<%=iIndex %>" runat="server" />
    </div>
<%}%>

SOLUTION (2013-02-12): I tried out all three answers below, sadly after I marked one as a solution. The winning one is a modified version of the Page_LoadControl(). Here is the code that works, and yes, I ran the code. Everything works.

// Load an array of controls onto a predefined panel.
for (int iIndex = 0; iIndex < 10; iIndex++)
{
    // Load the control.
    MyProject.Controls.MyControl ctlItem = (MyProject.Controls.MyControl)Page.LoadControl(@"/Controls/MyControl.ascx");

    // Initialize the control.
    ctlItem.MyIndex = iIndex;

    // Add the control to the panel.
    this.pnlItems.Controls.Add(ctlItem);
}

Here is the fixed aspx code.

<div id="divItems" runat="server" class="divItems">
    <dx:ASPxPanel ID="pnlItems" runat="server" Width="200px">
    </dx:ASPxPanel>
</div>

I tried doing, MyProject.Controls.MyControl ctlItem = new MyProject.Controls.MyControl(), however that does not work. I got a null excemption. Loading the control worked.

The answer, which I too hastilly marked as a solution, does not work. When ran the designer complained. Here is the code from the designer.

    /// <summary>
    /// ctlPurchases<%=iIndex %> control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::MyProject.Controls.MyControl ctlItem<%=iIndex %>;

The designer was unhappy about the <%...%> part. This solution has other problems. The cleanest one is using the Page_LoadControl.

1
  • I don't see an array anywhere in your code. Commented Feb 12, 2013 at 0:23

3 Answers 3

1

Can you use an ASP.NET Panel and use Page.LoadControl()?

for (int i = 0; i < 10; i++)
{
    pnlContent.Controls.Add(Page.LoadControl("ucDemo.ascx"));
}

This is in C# BTW.

Or if these UserControls will be data bound, you could try using a Repeater control.

Sign up to request clarification or add additional context in comments.

2 Comments

This time I did not rush things and tried out all three options. Two did not work, but this one did. I should add that "var d = new ucDemo()" is unnecessary. Page_LoadControl() returns a type of Control. See solution in my edited question. Thanks!
Thanks Sarah! I removed the unnecessary variable from my code snippet as well.
1

When I want multiple copies of my user control I usually follow the pattern below

<%for (Counta = 1; Counta <= 10; Counta++) {%>
<div id="divMyusercontrols<%=Counta%>" runat="server">
  <uc:myUsercontrol1 id="ctlTheControl<%=Counta%>" runat="server" />
</div>
<%}%>

The code above would give me 10 UserControls nested inside 10 div elements

UPDATE

Please note that I have used an on-line tool to convert the code from VB to c# So how accurate it is I don't know. Yet I don know it works for me in VB.

The VB Code is below for comparison

<%for Counta = 1 To 10%>
<div id="divMyusercontrols<%=Counta%>" runat="server">
  <uc:myUsercontrol1 id="ctlTheControl<%=Counta%>" runat="server" />
</div>
<%Next%>

6 Comments

Cool. That works. Thank you. I will add in the proper code behind for anyone reading that is interested.
Thank You, Sometimes Its a little difficult for me to convert to c/c# but its all well that you got my meaning. Great!!
This will work, but won't this make the code harder to read over time? Handling this in the code-behind will be easier to read, IMHO, and might be more flexible.
I was a bit too zealous in things. I should have compiled and ran the code first. I am using Visual Studio 2012 with .Net 4.0. The designer throws, and recreates if I delete the offending line, a errr on the ctlItem<%=iIndex %>. It hates that. Additionally, the design view cannot display the control. Unless, I am missing something, there is a problem. I will continue testing. Thanks rrjohnson85 for the comment. I am still curious if the code could work.
@rrjohnson85 I guess its down to each developers personal style of coding, some prefer to keep their code and document together in one file and others prefer to split the two up up into code behind and document. Each to their own I guess. Maybe the OP (Sarah) will just use the sample and adapt it to her own style Also Note that she mentions "Thank you. I will add in the proper code behind for anyone reading that is interested"
|
0

I think you can do in Page_Load:

  HtmlGenericControl control = FindControl("divMyusercontrols")
  var myControl = new MyControl();
  for(int i=0; i<numberOfUserControls; i++)
  {
     myControl.ID = "myUniqueID" + i; 
  }
  myControl.Controls.Add(myControl);

1 Comment

I will have to try. The last one came in first, so I tried that. I still have a lot to learn.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.