Philippe
Philippe

Reputation: 4051

How to add forms inputs in an unordered list element

I'm dynamically generating an asp form, and I would like to add the label and input elements inside a list.

For example, I would like to end up with something like:

<ul>
<li><label for="input"/><input id=input"/></li>
</ul>

To do this, I create a Label object and a TextBox object, then assign the AssociatedControlId property of the Label to link these. But I cannot add any of these in a ListItem, nor can I add these in the Controls collection of BulletedList...

Any ideas would be greatly apreciated.

Upvotes: 0

Views: 3589

Answers (2)

ChrisN
ChrisN

Reputation: 3413

The System.Web.UI.HtmlControls namespace has some useful controls.

In your aspx:

<asp:PlaceHolder ID="PlaceHolder1" runat="server" />

In your code behind:

HtmlGenericControl list = new HtmlGenericControl("ul");
for (int i = 0; i < 10; i++)
{
    HtmlGenericControl listItem = new HtmlGenericControl("li");
    Label textLabel = new Label();
    textLabel.Text = String.Format("Label {0}", i);
    listItem.Controls.Add(textLabel);
    // etc...
    list.Controls.Add(listItem);
}
PlaceHolder1.Controls.Add(list);

Works like a charm.

Upvotes: 4

Michael DeLorenzo
Michael DeLorenzo

Reputation: 1140

You could probably do something like this using a Repeater.

<asp:Repeater ID="rpt" runat="server">
    <HeaderTemplate>
        <ul>
    </HeaderTemplate>
    <ItemTemplate>
        <li>
            <label for='<%# string.Format("ctrl-{0}", Container.ItemIndex) %>'>label for ctrl #<%# Container.ItemIndex %></label>
            <input id='<%# string.Format("ctrl-{0}", Container.ItemIndex) %>' type="text" />                
        </li>
    </ItemTemplate>
    <FooterTemplate>
        </ul>
    </FooterTemplate>
</asp:Repeater>

If you need to add server controls to the list, you'll need to do something with the Repeater's ItemDataBound event.

Upvotes: 0

Related Questions