Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to programmatically add items to <UL> element?

Tags:

html

asp.net

I have a ASP.NET 2.0 app with an existing <UL>. I want to programmatically add items to it. I've already added the ID and runat="server" attributes.

like image 744
donde Avatar asked Jul 01 '10 14:07

donde


2 Answers

You can just create new HtmlGenericControls and add them into the Controls property of the UL control? So, given markup as follows:

<ul runat="server" id="foo_bar">
    <li>Item</li>
</ul>

You can do this (where itemList is a list of things you want to add as LIs):

foreach (var item in itemList)
{
    HtmlGenericControl newLi = new HtmlGenericControl("li");
    newLi.InnerText = item.DisplayText;
    foo_bar.Controls.Add(newLi);
}

If you were rending out an array of strings, i.e:

string[] itemList = new string[] { "1", "2", "3" };
foreach (string item in itemList)
{
    HtmlGenericControl newLi = new HtmlGenericControl("li");
    newLi.InnerText = item;
    foo_bar.Controls.Add(newLi);
}

You would see the following results (with my original markup):

  • Item
  • 1
  • 2
  • 3
like image 112
djdd87 Avatar answered Sep 17 '22 23:09

djdd87


The easiest way to add items to an unordered list is to use the repeater control.

You can bind your list of items to the repeater and then output each list item as required.

 <asp:Repeater ID="rpt1" Runat="server">
 <HeaderTemplate>
  <ul>
 </HeaderTemplate>

  <ItemTemplate>
    <li>
      <%# DataBinder.Eval(Container.DataItem, "Item") %>
   </li>
  </ItemTemplate>

  <FooterTemplate>
    </ul>
  </FooterTample>
 </asp:Repeater>

Then in your C# (or whatever server-side language you're using) you do:

DataSet listItems = GetTheListItemsMethod();

rptr1.DataSource = listItems;
rptr1.DataBind();
like image 45
Jamie Dixon Avatar answered Sep 21 '22 23:09

Jamie Dixon