使用 asp:Repeater 生成表格行:
<asp:repeater ID="announcementsRepeater" OnItemDataBound="announcementsRepeater_ItemDataBound" runat="Server">
<itemtemplate>
<tr id="announcementRow" class="announcementItem" runat="server">...</tr>
</itemtemplate>
</asp:repeater>
现在在数据绑定(bind)中,我想用不同的 css 类标记“未读”公告,以便网络专家可以执行他想要区分已读和未读公告的任何样式:
protected void announcementsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
return;
// get the associated data item
Announcement announcement = (Announcement)e.Item.DataItem;
WebControl row = (WebControl)e.Item.FindControl("announcementRow");
if (row != null)
row.CssClass = row.CssClass + " announcementItemUnread";
}
除了运行时转换失败:
System.InvalidCastException occurred
Message="Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlTableRow' to type 'System.Web.UI.WebControls.WebControl'."
事实证明HtmlTableRow
具有与 WebControl
不同的父层次结构:
HtmlTableRow
: HtmlContainerControl
: HtmlControl
: System.Web.UI.Control
WebControl 的最终来源
WebControl
: System.Web.UI.Control
所以我更改了代码以尝试改用 System.Web.UI.Control:
Control row = (Control)e.Item.FindControl("announcementRow");
if (row != null)
row.CssClass = row.CssClass + " announcementItemUnread";
但是Control
不包含 CssClass
的定义:
'System.Web.UI.Control' does not contain a definition for 'CssClass'
那么我如何为 <TR>
设置 css 类名呢? DataBind 期间的元素?
最佳答案
HtmlControl htmlRow = (HtmlControl)row;
htmlRow.Attributes["class"] = htmlRow.Attributes["class"] + " announcementItemUnread";
关于ASP.NET:如何在 DataBind 期间设置控件的 css 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/183415/