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.
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):
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With