为datalist中的item添加样式

时间:2010-10-21 11:14:58

标签: asp.net

我有Datalist并且当我点击它以向用户显示他选择此项目时我想要项目样式我做了我的代码但是当我选择项目时它没有任何样式

protected void DataList3_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)    
            e.Item.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";

        e.Item.Attributes["onmouseout"] = "this.style.textDecoration='none';";    
        e.Item.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.DataList3, "Select$" + e.Item.ItemIndex);
    }

1 个答案:

答案 0 :(得分:1)

e.Item.Attributes不会呈现为html,它们只是不显示。添加某种控件,例如面板:

<asp:DataList ID="DataList3" runat="server">
    <ItemTemplate>
        <asp:Panel ID="Panel1" runat="server">
            <%#Container.DataItem%>
        </asp:Panel>
    </ItemTemplate>
</asp:DataList>

然后改变你的ItemDataBound事件

protected void DataList3_ItemDataBound(object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {   
        Panel p = (Panel)e.Item.FindControl("Panel1");
        p.Attributes.Add("onmouseover", "this.style.cursor='hand';this.style.textDecoration='underline';");
        p.Attributes.Add("onmouseout", "this.style.textDecoration='none';");    
        // ?? p.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.DataList3, "Select$" + e.Item.ItemIndex);
    }    
}

对于问题的样式部分,更好的解决方案是使用css和类名,将<ItemStyle CssClass="item" />添加到数据列表中。

的CSS:

.item{cursor:pointer;text-decoration:underline;}
.item:hover{text-decoration:none;}

如果你问我,“onlick”应该由LinkBut​​ton处理,但是我并不完全明白你在尝试做什么。

相关问题