Question

I need to generate the following in ASP.NET page. What's the best, easiest way to do that?

Simplified example. So to custom property I need to pass string which would include index (i) to the property of the control. I could do it from codebehind, but it would be simpler and easier if I could keep it in .aspx file.

<table>
<% 
    for( var i = 0; i < 10; i++ )
{
%><tr>
    <td>
        <cc1:CustomControl runat="server" CustomProperty="SomeText[<% i %>]"/>
    </td>
</tr>
<% } %>
</table>

Essentially I need to pass a custom, not predetermined value to the asp.net control.

Was it helpful?

Solution

This probably won't work how you expect it to. Instead, add a place holder like this:

<table>
  <asp:PlaceHolder id="RowPlaceHolder" runat="server" />
</table>

And then in your code behind:

for (int i = 0;i<10;i++)
{
   var tr = new HTMLTableRow();
   var td = new HTMLTableCell();
   var Custom = (CustomControl)LoadControl("MyControl.ascx");
   Custom.id="Custom" + i.ToString();
   Custom.CustomProperty = "SomeText[" + i.ToString() + "]";

   td.Controls.Add(Custom);
   tr.Controls.Add(td);
   RowPlaceHolder.Controls.Add(tr);
}

Going deeper, if the number 10 really is hard-coded, you'll find things much easier to deal with in the long run if you just go ahead and copy 10 entries for your control into the aspx markup manually. Dynamic controls in ASP.Net webforms are rife with pitfalls and gotchas.

If the number comes from some legitimate datasource, then you're likely better off actually using that datasource and binding it to a data control like a repeater.

OTHER TIPS

<%= i %>

Should work for you.

You could rock out with a repeater and use the Container.ItemIndex,

<asp:Repeater ID="rpt" runat="server">
    <HeaderTemplate>
        <table>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td> 
                <cc1:CustomControl runat="server" CustomProperty="SomeText[<%# Container.ItemIndex %>]"/>
            </td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top