[英]C# How to add an item to a listview if the item exists but the subitem is different?
[英]How to add class in c#(server) to ListView li item
我在服務器中使用Linq我這樣填充我的列表
selected MenuId=3;
ul_HeaderMenu.DataSource = data.TABLE_MENUS.ToList();
ul_HeaderMenu.DataBind();
這個客戶端代碼
<asp:ListView ID="ul_HeaderMenu" runat="server" ClientIDMode="Static">
<ItemTemplate >
<li class="li-HeaderMenu" runat="server" ><%# Eval("Name") %>
<div class="TopMenuActive"></div>
</li>
<ItemTemplate>
</asp:ListView>
我需要在服務器中構建我的類添加類,有些人認為這樣
selected MeduId=3;
ul_HeaderMenu.DataSource = data.TABLE_MENUS.ToList();
ul_HeaderMenu.DataBind();
ul_HeaderMenu.ElementAt[3]AddClass('test');
我只是找到了向li添加類的方法。
您可以在列表中使用itemdatabound事件
<asp:ListView OnItemDataBound="YourListView_ItemDataBound" ID="ul_HeaderMenu" runat="server" ClientIDMode="Static">
<ItemTemplate >
<li ID="listItem" class="li-HeaderMenu" runat="server" ><%# Eval("Name") %>
<div class="TopMenuActive"></div>
</li>
<ItemTemplate>
</asp:ListView>
然后在代碼背后,這樣的事情;
protected void YourListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
HtmlGenericControl myLi = (HtmlGenericControl)e.Item.FindControl("listItem");
myLi.Attributes.Add("class", myLi.Attributes["class"].ToString() + " yournewclass");
}
ListView由ItemTemplate部分定義的項目組成,而不是li元素。 因此,當您通過索引從ListView獲取元素時,首先需要找到li,然后才能向其添加類。 因此,您需要在項目上使用FindControl
方法來獲取li。
現在,這里有一些問題。
ListView沒有ElementAt
方法,它的Items
集合有它,但是,我仍然會使用ul_HeaderMenu.Items[3]
來獲取索引處的元素。
如果你想使用FindControl
方法,你需要在你的ItemTemplate中為你的li添加一個id,你將傳遞給FindControl獲取li。
AddControl
方法不存在,您必須在li上使用Attributes
集合來更改class屬性。 在這里你必須要小心,因為你想保留已經存在的類,所以你必須連接字符串,但是你不想多次添加同一個類,因此最好是你創建了一個幫助方法獲取字符串並使用添加的類返回的AddClass。
您可以隨時執行所有這些操作,但通常您會想要使用ItemDataBound
事件,如同Lars Anundskas在此期間所述。
最后,雖然你可以自由地使用你喜歡的任何約定,但我個人覺得你的套管慣例令人困惑 - 你可以在這里閱讀微軟的建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.