从添加codebehind C#Asp.net到列表

问题描述:

我有一个ASPX页面UL列表:

I have a UL list in a ASPX page:

<ul id="tabs">
 <li id="tab1"><a href="ztab1.htm">Tab 1</a></li>
 <li id="tab2"><a href="ztab2.htm">Tab 2</a></li>
 <li id="tab3"><a href="ztab3.htm">Tab 3</a></li>
 <li id="tab4"><a href="ztab4.htm">Tab 4</a></li>
 </ul> 

我想从codebehind动态添加列表项,包括每一个新的列表项中的href条目。

I would like to add list items dynamically from codebehind, including the href entry for each new list item.

如何?

您需要标记您的UL作为服务器端控制,则治其标新项目为 HtmlGenericControl 将其插入控件集合:

You need to mark your ul as a server side control, then treat the 'new item' as a HtmlGenericControl and insert it into the control collection:

<ul runat="server" id="tabs"> 

要添加的项目,创建一个新的元素,并添加它:

To add the item, create a new element and add it:

HtmlGenericControl li = new HtmlGenericControl("li");
tabs.Controls.Add(li);

HtmlGenericControl anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", "page.htm");
anchor.InnerText = "TabX";

li.Controls.Add(anchor);