摘要:Code Behind C# ul li
出處 : http://stackoverflow.com/questions/3530965/add-to-list-from-codebehind-c-sharp-asp-net
可以自訂 Code Behind C# ul li 這篇解決我的問題
You can create a dynamic UL by using an asp:Repeater
Control
You can use repeater in following way, in your .aspx
file
<asp:Repeater ID="menu_ul_1" runat="server">
<HeaderTemplate>
<ul class="my-menu">
</HeaderTemplate>
<ItemTemplate>
<li>
<a href='<%# Eval("href_li")%>'>
<%# Eval("DisplayText")%></a>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
And you can put dynamic data via code behind in .aspx.cs
file
protected void Page_Load(object sender, EventArgs e)
{
DataTable newsDataTable = new DataTable();
// add some columns to our datatable
newsDataTable.Columns.Add("href_li");
newsDataTable.Columns.Add("DisplayText");
for (int i = 1; i <= 5; i++)
{
DataRow newsDataRow = newsDataTable.NewRow();
newsDataRow["href_li"] = "?sc=item_" + i;
newsDataRow["DisplayText"] = "List Item # "+i;
newsDataTable.Rows.Add(newsDataRow);
}
menu_ul_1.DataSource = newsDataTable;
menu_ul_1.DataBind();
}
Result: You will get following html through this code
<ul class="my-menu">
<li><a href='?sc=item_1'>List Item # 1</a> </li>
<li><a href='?sc=item_2'>List Item # 2</a> </li>
<li><a href='?sc=item_3'>List Item # 3</a> </li>
<li><a href='?sc=item_4'>List Item # 4</a> </li>
<li><a href='?sc=item_5'>List Item # 5</a> </li>
</ul>