donde
donde

Reputation: 91

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

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.

Upvotes: 9

Views: 19762

Answers (4)

Chuckie
Chuckie

Reputation: 135

Define an unordered list inside a div tag and add an id field and runat=server to the tag so you can get to the control from the code behind page.

Code behind code example

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim y As ArrayList = New ArrayList()
    y.Add("first")
    y.Add("second")
    y.Add("three")

    For Each z As String In y
        Dim x2 As HtmlGenericControl = New HtmlGenericControl("li")
        x2.InnerText = z.ToString
        ted.Controls.Add(x2)
    Next

End Sub

Upvotes: 0

Dave Thieben
Dave Thieben

Reputation: 5427

there is also System.Web.UI.WebControls.BulletedList

you can either bind to a datasource

var bulletedList = new BulletedList();
bulletedList.DataSource = myData;
bulletedList.DataBind();

or add items individually to the Items collection

bulletedList.Items.Add( "item1" );
bulletedList.Items.Add( "item2" );

don't forget to add it to something on the page, or you'll never see it

Page.Controls.Add( bulletedList );

Upvotes: 0

djdd87
djdd87

Reputation: 68456

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

Upvotes: 19

Jamie Dixon
Jamie Dixon

Reputation: 53991

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();

Upvotes: 3

Related Questions